I am adding/removing dynamically created child components from parent component. This is my child component:
<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>
It's being used in the parent component like this:
<div #newUserParent></div>
This is the parent ts file:
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;
}
}
Problem Statement The problem that I am facing here is that I know how to add components and how each component has a Component Factory associated with it and how its view gets created in the ViewContainerReference. What I fail to understand is how we can traverse through ViewContainerReference and get back the components and call their functions. I am able to access the properties through the code I have written above, but it seems wrong. There must be a better approach. I have also gone through the class of ViewContainerReference and couldn't understand which function can help me out here