In my home.html:
<p #pmessage>msg 1</p>
<p #pmessage>msg 2</p>
<p #pmessage>msg 3</p>
<p #pmessage>msg 4</p>
In my home.ts:
export class HomePage {
@ViewChildren('pmessage') pMessages;
constructor() {
//using first works, result <p>msg 1</p>
console.log(this.pMessages.first.nativeElement);
//using last also works, result <p>msg 4</p>
console.log(this.pMessages.last.nativeElement);
//How can I get the two in the middle? i.e <p>msg 2</p> and <p>msg 3</p>
//this isn't working
console.log(this.pMessage[1].nativeElement);
//this either isn't working
console.log(this.pMessage.1.nativeElement);
}
}
Please help. Thanks.
The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.
ViewChild is used to select an element from component's template while ContentChild is used to select projected content.
Another critical difference is that @ViewChild returns a single native DOM element as a reference, while the @ViewChildren decorator returns the list of different native DOM elements in the form of QueryList , which contains the set of elements.
ViewChildlinkProperty decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.
There is typo in accessing pMessages
. The 's' is missing.
`console.log(this.pMessages[1].nativeElement);`
Also you should access viewChildren in ngAfterViewInit
or later. The variable could be undefined
before that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With