Angular2 Wait DOM element to load
10,682
The answer of @Andrei works, but in my opinion there's a better and more elegant solution.
Just use a combination of @ViewChild()
and setters.
For example:
// component.html
<ng-el ... #myElement>
// component.ts
@ViewChild('myElement') set(el) {
if (el) {
console.log('element loaded!');
}
}
Author by
Yhlas
Updated on November 30, 2022Comments
-
Yhlas over 1 year
I have Component which has a member array variable. This array is bind to DOM with *ngFor. When I add new variable to array my view changes accordingly. Array holds tab names and initially it is set to have only 1 tab. When I refresh page array reinitialized which is what I was expecting. But when I logout and then log back in(router navigation) I see all previous tabs. It is weird to me, because if I
console.log(myTabs)
array has only 1 element(homeTab).UPDATE:
.html
<div style="display: table-caption" id="notify-tabs"> <ul class="nav nav-tabs" role="tablist" id="nav-bar"> <li role="presentation" data-toggle="tab" id="homeTab" [class.active]="activeTab==='homeTab'"><a (click)="setValues('home')">Home</a> <li role="presentation" *ngFor="let tab of myTabs" data-toggle="tab" id={{tab}} [class.active]="activeTab===tab.toString()"><a (click)="setValues(tab)">{{tab}}</a> </ul> </div>
.component.ts
@Component({
selector: 'notify-homepage', templateUrl: 'app/home/home.component.html', styleUrls: ['styles/css/bootstrap.min.css', 'styles/home.css'], directives: [DynamicComponent, TileComponent, MapComponent, HeaderComponent, ConversationComponent, ROUTER_DIRECTIVES] }) export class HomeComponent{ public myTabs: number[] = [21442]; public activeTab: string = 'homeTab'; ngOnInit() { //Assume fully operating MapService here this.subscription = this.mapService.conversationId.subscribe( (id: number) => { this.myTabs.push(id); this.setValues(id); this.activeTab = id.toString(); }) } ngOnDestroy() { this.subscription.unsubscribe(); ... } }
map.service.ts
@Injectable() export class MapService { private conversationIdSource = new ReplaySubject<number>(); public conversationId = this.conversationIdSource.asObservable(); ... showConversation(id: number) { this.conversationIdSource.next(id); } }
-
Yhlas over 7 yearsI am currently using BehaviourSubject from Rxjs for change detection. My problem is that I have to wait until this change will show up on the view and then act upon it.
-
Andrei Zhytkevich over 7 yearsplease add code of your
service
because it's not clear whatthis.mapService.conversationId
is. Also, it seems to me that router handling does something wrong.