Saturday, August 25, 2018

@ViewChildren in between components to Components

child.components.ts

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
public var_one:string;
public var_two:string;

constructor() {
this.var_one="This is coming from Child Component";
this.var_two="Text Coming from Child Component."
}

ngOnInit() { }

}

child.component.html

<h1>{{var_one}}</h1>
<h1 style="color: brown">{{var_two}}</h1>


parent.components.html

<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
<button (click)="clickMe()">Click Me Btn</button>


parent.components.ts

import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})

export class ParentComponent implements OnInit {
// @ViewChild(ChildComponent)
// private _child:ChildComponent;

@ViewChildren(ChildComponent)
private _child:QueryList<ChildComponent>=new QueryList;
private my_array:Array<any>;
constructor() { }
ngOnInit() {
}
public clickMe():any{

// this._child.var_one = "Message from Parent Component";
// this._child.var_two = "Marquee coming from Parent Component"

// this.my_array[0].var_one="Hello One";
//this.my_array[0].var_two="Hi....1";
// this.my_array[1].var_one="Hello Two";
//this.my_array[1].var_two="Hi...2";
for(var i:number=0; i<this.my_array.length;i++){
this.my_array[i].var_one="Hello World";
this.my_array[i].var_two="Hi....";
}
}

ngAfterViewInit(){
this.my_array=this._child.toArray();
}
}


Out Put



after click button   output




No comments:

Post a Comment