Angular 2在动态添加组件时将数据传递给组件

前端之家收集整理的这篇文章主要介绍了Angular 2在动态添加组件时将数据传递给组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在点击按钮时动态添加了一个组件.

下面是我的小部件的代码.将color属性设置为输入的简单div.

Widget.tmpl.html

div class="{{color}}" (click)="ChangeColor()"

在Widget组件中,我将颜色作为输入.当我手动添加它时,此组件工作正常.但现在我正在尝试动态添加组件,还需要将颜色值传递给窗口小部件组件.

下面是app.component.ts中的代码,我在按钮单击时调用addItem().

app.component.ts

export class AppComponent  {
  @ViewChild('placeholder',{read: ViewContainerRef}) viewContainerRef;
  private componentFactory: ComponentFactory<any>;

  constructor(componentFactoryResolver: ComponentFactoryResolver,compiler: Compiler) {
    this.componentFactory = componentFactoryResolver.resolveComponentFactory(MyAppComponent);

  }

  addItem () {
   this.viewContainerRef.createComponent(this.componentFactory,0);
  }

 public  myValue:string = 'red';

 onChange(val: any) { this.myValue = val; } }

在addItem()方法中,我动态地将我的小部件组件添加到我的视图中.该组件得到了很好的补充.但问题是如何在动态添加时传递color属性.基于我在创建窗口小部件时传递的颜色,我希望它以红色或绿色等显示.如何在此场景中绑定属性

以下是一些代码

export class MyAppComponent { 

    @Input() color; 
    @Output('changes') result: EventEmitter<any> = new EventEmitter(); 

    public constructor() { 
    }

    ChangeColor() {
        this.ToggleColor();
        this.result.emit(this.color);// Emitting the color to the parent.        
    }

    ToggleColor() {
        if (this.color == "red")
            this.color = "blue";
        else
            this.color = "red";
    }
}

在上面的代码中,我将我的颜色发送到父app.component.ts,但由于我已动态添加了widget组件,我不知道在哪里添加代码(changes)=“onChange($event)”.我尝试在div中添加代码,如下所示:

<div class="{{color}}" (click)="ChangeColor()" (changes)="onChange($event)"></div>

但它不起作用.

解决方法

var cmpRef = this.viewContainerRef.createComponent(this.componentFactory,0);
cmpRef.instance.someProp = 'someValue';
cmpRef.instance.someObservable.subscribe(val => this.someProp = val);

猜你在找的Angularjs相关文章