Bosco Xeno πŸš€

How should I use the new static option for ViewChild in Angular 8

February 16, 2025

πŸ“‚ Categories: Programming
How should I use the new static option for ViewChild in Angular 8

Angular eight launched a important alteration to however builders work together with constituent views done the @ViewChild and @ViewChildren decorators. The instauration of the static place gives much power complete once a position question is resolved, addressing communal points associated to timing and alteration detection. Knowing this fresh characteristic is indispensable for immoderate Angular developer aiming to physique strong and businesslike purposes. This article volition delve into the nuances of the static action, explaining once and wherefore you ought to usage it, and show applicable examples to solidify your knowing.

Knowing the static Place

Anterior to Angular eight, the solution of @ViewChild queries may beryllium unpredictable, frequently starring to contest situations and surprising behaviour. This was peculiarly actual once dealing with dynamically rendered contented oregon elements projected utilizing ng-contented. The static place addresses this by providing express power complete the timing of question solution. Mounting static: actual resolves the question last alteration detection has accomplished for the actual constituent’s position, guaranteeing entree to the queried parts. Conversely, mounting static: mendacious (the default successful Angular 9 and future) resolves the question last the alteration detection rhythm of the genitor constituent completes, permitting for entree to parts inside projected contented.

Selecting the accurate worth relies upon wholly connected your usage lawsuit. If you’re querying parts inside your constituent’s template straight, static: actual is frequently adequate. Nevertheless, if you’re interacting with parts projected from a genitor constituent, static: mendacious is essential to guarantee they’re disposable.

Utilizing static: actual for Section Components

Once you demand to entree a kid constituent oregon component inside your constituent’s template, the static: actual action simplifies the procedure. This is peculiarly utile once you demand to work together with the component last initialization, for illustration, calling a methodology connected a kid constituent oregon manipulating its properties.

Illustration:

@ViewChild('myChild', { static: actual }) myChildComponent: MyChildComponent; ngAfterViewInit() { this.myChildComponent.someMethod(); }Successful this illustration, myChildComponent is assured to beryllium disposable successful ngAfterViewInit.

Utilizing static: mendacious for Projected Contented

The static: mendacious mounting is important once dealing with contented projected by way of ng-contented. Due to the fact that projected contented is rendered by the genitor constituent, it’s not disposable till last the genitor’s alteration detection rhythm completes.

Illustration:

@ViewChild('projectedElement', { static: mendacious }) projectedElement: ElementRef; ngAfterViewInit() { console.log(this.projectedElement); // Present disposable }Champion Practices and Communal Pitfalls

Selecting the correct static worth is cardinal to avoiding runtime errors and sudden behaviour. A communal error is utilizing static: actual once interacting with projected contented, starring to null oregon undefined errors. Cautiously see the root of the component you’re querying.

  • Ever analyse whether or not you are querying domestically oregon from projected contented.
  • Usage static: actual for components inside your constituent’s template.
  • Usage static: mendacious for projected contented oregon once the component’s beingness is conditional.

Present’s a adjuvant array summarizing the cardinal variations:

  1. static: actual: Resolves question last constituent position initialization.
  2. static: mendacious: Resolves question last genitor constituent alteration detection.

Infographic Placeholder: (Ocular cooperation of static: actual vs. static: mendacious solution timing)

Larn much astir Angular constituent action.Precocious Usage Circumstances and Alternate options

Piece @ViewChild with the static emblem covers galore eventualities, another approaches mightiness beryllium much appropriate for analyzable conditions. For case, once dealing with aggregate dynamic elements oregon components, @ViewChildren mixed with an observable offers much flexibility. This permits you to respond to adjustments successful the queried components complete clip.

Different alternate is to leverage the ContentChild decorator which is particularly designed for querying projected contented. This tin simplify your logic and better readability, particularly once dealing with nested constituent constructions.

Outer Sources

FAQ

Q: What occurs if I usage static: actual with dynamically created components?

A: If the component doesn’t be throughout the first position initialization, utilizing static: actual volition consequence successful the question returning undefined. You’ll demand to usage static: mendacious oregon a antithetic attack to grip dynamic contented.

The static action successful Angular’s @ViewChild decorator offers important power complete question timing. By knowing the discrimination betwixt static: actual and static: mendacious, you tin debar communal pitfalls and physique much strong Angular functions. Retrieve to take the due mounting based mostly connected whether or not you are querying components inside your constituent’s template oregon projected from a genitor constituent. Research the offered sources and experimentation with antithetic approaches to genuinely maestro this almighty characteristic and optimize your Angular improvement workflow. Commencement gathering much businesslike and predictable Angular purposes present by leveraging the afloat possible of @ViewChild.

Question & Answer :
However ought to I configure the fresh Angular eight position kid?

@ViewChild('searchText', {publication: ElementRef, static: mendacious}) national searchTextInput: ElementRef; 

vs

@ViewChild('searchText', {publication: ElementRef, static: actual}) national searchTextInput: ElementRef; 

Which is amended? Once ought to I usage static:actual vs static:mendacious?

Successful about circumstances you volition privation to usage {static: mendacious}. Mounting it similar this volition guarantee question matches that are babelike connected binding solution (similar structural directives *ngIf, and so on...) volition beryllium recovered.

Illustration of once to usage static: mendacious:

@Constituent({ template: ` <div *ngIf="showMe" #viewMe>Americium I present?</div> <fastener (click on)="showMe = !showMe"></fastener> ` }) export people ExampleComponent { @ViewChild('viewMe', { static: mendacious }) viewMe?: ElementRef<HTMLElement>; showMe = mendacious; } 

The static: mendacious is going to beryllium the default fallback behaviour successful Angular 9. Publication much present and present

The { static: actual } action was launched to activity creating embedded views connected the alert. Once you are creating a position dynamically and privation to acces the TemplateRef, you received’t beryllium capable to bash truthful successful ngAfterViewInit arsenic it volition origin a ExpressionHasChangedAfterChecked mistake. Mounting the static emblem to actual volition make your position successful ngOnInit.

However:

Successful about another circumstances, the champion pattern is to usage {static: mendacious}.

Beryllium alert although that the { static: mendacious } action volition beryllium made default successful Angular 9. Which means that mounting the static emblem is nary longer essential, except you privation to usage the static: actual action.

You tin usage the angular cli ng replace bid to routinely improve your actual codification basal.

For a migration usher and equal much accusation astir this, you tin cheque present and present

#What is the quality betwixt static and dynamic queries? The static action for @ViewChild() and @ContentChild() queries determines once the question outcomes go disposable.

With static queries (static: actual), the question resolves erstwhile the position has been created, however earlier alteration detection runs. The consequence, although, volition ne\’er beryllium up to date to indicate modifications to your position, specified arsenic modifications to ngIf and ngFor blocks.

With dynamic queries (static: mendacious), the question resolves last both ngAfterViewInit() oregon ngAfterContentInit() for @ViewChild() and @ContentChild() respectively. The consequence volition beryllium up to date for adjustments to your position, specified arsenic adjustments to ngIf and ngFor blocks.


A good usage-lawsuit for utilizing static: actual, is if you are utilizing fromEvent to hindrance to an component outlined successful the template. See the pursuing template:

<div [ngStyle]="thumbStyle$ | async" #thumb></div> 

You tin past grip occasions connected this component with out the demand of utilizing subscriptions oregon init hooks (if you don’t privation to oregon can not usage angular case binding):

@Constituent({}) export people ThumbComponent { @ViewChild('thumb', { static: actual }) thumb?: ElementRef<HTMLElement>; readonly thumbStyle$ = defer(() => fromEvent(this.thumb, 'pointerdown').tube( switchMap((startEvent) => fromEvent(papers, 'pointermove', { passive: actual }) // change to appropriate positioning )); } 

It is crucial to usage defer. This volition brand certain the observable is lone resolved once it’s subscribed to. This volition hap earlier the ngAfterViewInit will get triggered, once the async tube subscribes to it. Due to the fact that we are utilizing static: actual, the this.thumb is already populated.