如何解决Angular 2中动态添加组件的值?

时间:2017-02-13 08:17:54

标签: angular typescript components

我有模态组件包含设备信息,我在其中动态添加下面给出的用户<user.component.ts>。它已被添加&amp;成功呈现,但不知何故,我无法在模态<modal.component.ts>中获取所选用户的详细信息。

modal.component.ts

@Component({
  selector: 'modal',
  templateUrl: './modal.component.html'
})
export class ModalComponent {
    constructor(injector: Injector, 
            componentFactoryResolver: ComponentFactoryResolver) {}

    @ViewChild('userContainer', { read: ViewContainerRef }) userContainer: ViewContainerRef;
    cmp: ComponentRef<UserListComponent>;

    addComponent() {
        const factory = this.componentFactoryResolver.resolveComponentFactory(UserListComponent);
        this.cmp = this.userContainer.createComponent(factory);
    }
}

user.component.ts

@Component({
  selector: 'user',
  templateUrl: `<select [(ngModel)]="user">
           <option *ngFor="let user of users" [ngValue]="user">{{user.name}}</option>
         </select>`
})
export class UserComponent {...}

1 个答案:

答案 0 :(得分:2)

使用EventEmitterObservable在更改时发出值

@Component({
  selector: 'user',
  templateUrl: `<select [(ngModel)]="user">
           <option *ngFor="let user of users" [ngValue]="user">{{user.name}}</option>
         </select>`
})
export class UserComponent {
    @Output() userChange:EventEmitter = new EventEmitter();

    private _user:any;
    get user () {
      return this._user;
    }

    set user(val) {
      this._user = val;
      this.userChange.emit(val);
    }
}

并订阅以下更改:

addComponent() {
    const factory = this.componentFactoryResolver.resolveComponentFactory(UserListComponent);
    this.cmp = this.userContainer.createComponent(factory);
    this.cmp.instance.userChange.subscribe(val => console.log(val));
}