【发布时间】:2017-01-07 16:45:23
【问题描述】:
我已经在点击按钮时动态添加了一个组件。
下面是我的小部件的代码。将颜色属性设置为输入的简单 div。
Widget.tmpl.html
div class="{{color}}" (click)="ChangeColor()"
在 Widget 组件中,我将颜色作为输入。当我手动添加它时,这个组件工作正常。但是现在我正在尝试动态添加组件,并且还需要将颜色值传递给 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() 方法中,我动态地将我的小部件组件添加到我的视图中。该组件被很好地添加。但问题是动态添加时如何传递颜色属性。根据我在创建小部件时传递的颜色,我希望它以红色或绿色等显示。如何在这种情况下进行属性绑定?
这里是一些代码:
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,但由于我已经动态添加了小部件组件,所以我不知道在哪里添加此代码 (changes)="onChange($event)"。我尝试在 div 中添加此代码,如下所示:
<div class="{{color}}" (click)="ChangeColor()" (changes)="onChange($event)"></div>
但它不起作用。
【问题讨论】:
标签: angular