Я хочу получить номер вхождения компонента.Менас хочет знать, сколько раз этот конкретный компонент рендерит?
На самом деле, я сделал тостер и хочу знать, сколько раз он отображается?
Мои коды:
main.component.ts:
<toster-component [message]="'this is toster message'" [type]="'danger'" [duration]="'15'"> </toster-component>
<toster-component [message]="'this is toster message 2'" [type]="'info'
[duration]="'5'"> </toster-component>
toster.component.ts:
import { Component,Input,OnInit,ContentChildren,ElementRef,QueryList } from '@angular/core';
@Component({
selector: 'toster-component',
templateUrl: './toster.component.html',
styleUrls: ['./toster.component.css'],
});
export class TosterComponent implements OnInit {
public isShow:any=true;
public TabItem:any;
@Input() message:string; // Will show the message.
@Input() type:string; // What type will decide the style of this toster.
@Input() duration:number; // If duration ( In second ) is available the it will show till duration otherwise it will show permanently till manually closed
@ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;
ngAfterContentInit() {
console.log("Length: ",this.tosterComponents.toArray().length);
}
ngOnInit(){
this.message=this.message?this.message:'Test Message';
this.type=this.type?this.type:'info';
if(this.duration>0){
setTimeout(()=>{
this.isShow=false;
},this.duration*1000);
}
}
}
В приведенном выше коде я использую следующий код:
@ContentChildren(TosterComponent, {read: ElementRef}) tosterComponents:QueryList<TosterComponent>;
ngAfterContentInit() {
console.log("Length: ",this.tosterComponents.toArray().length); // I want to print the instance of this component.
}
для достижения того же самого, но его показ только 1 .Но это должно быть 2 , потому что его используют 2 раза в main.component.ts .