访问父模板中的以编程方式创建的子组件 - Angular 4

时间:2018-01-17 18:12:34

标签: angular typescript components

我正在从父组件添加/删除动态创建的子组件。这是我的孩子组成部分:

<div class="form-container">
<div class="form-item">
    <label class="edit-label" for="name">Name</label>
    <input type="text" class="edit-input" name="name" placeholder="John Doe" [formControl]="name" required>
</div>
<div class="form-item">
    <label class="edit-label" for="email">Email</label>
    <input type="email" class="edit-input" name="email" placeholder="johndoe@gmail.com" [formControl]="email" required>
</div>
<div class="form-item">
    <label class="edit-label" for="contact">Mobile Number</label>
    <input type="text" class="edit-input" name="contact" placeholder="03xx-xxxxxxx" [formControl]="contact" required>
</div>
<div class="form-item" *ngIf = "showRemove != false">
    <button type="button" class="btn btn-default btn-danger"
    (click)="removeObject()" > Remove</button>
</div>

它在父组件中使用如下:

<div #newUserParent></div>

这是父ts文件:

export class AddUserComponent implements OnInit {

 selectedMode = "existing";
 @ViewChild('newUserParent', { read: ViewContainerRef }) container:     ViewContainerRef; 

  users: IMultiSelectOption[];
  usersModel: number[];
  usersSettings: IMultiSelectSettings = {
  enableSearch: true
  }

  constructor(public activeModal: NgbActiveModal, 
          private _cfr: ComponentFactoryResolver) {}

  addComponent(showRemove = true) {
   console.log('adding component');
   //check and resolve the component
   var comp = this._cfr.resolveComponentFactory(NewUserComponent);
   //create component inside container
   var newUserComponent = this.container.createComponent(comp);
   newUserComponent.instance._ref = newUserComponent;
   newUserComponent.instance.showRemove = showRemove;
 }

 addUser() {
   console.log('add user');
   //dynamically go through the components and get the 
 }

 isValid() {
   var isValid = true;
   console.log(this.container.length); //returns the no. of components added
   //traverse through the components and see if they are valid or not
   for(let index = 0; index<this.container.length; index++) {

    // I want to basically go through the components and call their public functions and also access their public properties
    let component = this.container.get(index); console.log(component);
    let instance = component['_view']['nodes'][1];
    console.log(instance);
    // isValid = component.instance.isValid();
   }
   return isValid;
 }

}

问题陈述 我在这里面临的问题是,我知道如何添加组件以及每个组件如何与其关联的组件工厂以及如何在ViewContainerReference中创建其视图。我无法理解的是我们如何遍历ViewContainerReference并获取组件并调用它们的函数。我可以通过上面编写的代码访问属性,但似乎错了。必须有一个更好的方法。我也经历过ViewContainerReference类,无法理解哪个函数可以帮助我

1 个答案:

答案 0 :(得分:0)

我最终使用了@ AngularInDepth的方法。第一个对我来说没有用,因为我无法找到背景,但第二个没有找到。我试图做同样的事情,但不是添加&#39;实例&#39;在数组中的组件中,我将整个(this.container.createComponent(comp))推入一个导致我出现问题的数组中。