Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @ViewChildren in Angular2? [duplicate]

Tags:

angular

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.

like image 357
Vicheanak Avatar asked Jul 01 '16 12:07

Vicheanak


People also ask

Why do we use @ViewChild in angular2?

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.

What is the difference between ViewChild () and ContentChild ()?

ViewChild is used to select an element from component's template while ContentChild is used to select projected content.

What is the difference between ViewChild and ViewChildren?

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.

What is ViewChild () in Angular?

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.


1 Answers

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

like image 66
Arpit Agarwal Avatar answered Oct 30 '22 21:10

Arpit Agarwal