如何通过HTML设置Angular2/4类变量?循环赋值失效问题求助
Got it, let's fix that ngVar directive so it works reliably in loops. The issue with your current code is that it's incomplete—you're not properly setting up the template context, updating it when values change, or handling the "as" alias syntax correctly. Here's a complete, working implementation that solves all those problems:
Fixed ngVar Directive Code
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core'; // Define a context interface to hold our variable and alias interface NgVarContext { ngVar: any; $implicit: any; [key: string]: any; // Allow dynamic alias properties } @Directive({ selector: '[ngVar]', }) export class VarDirective { private context: NgVarContext = { ngVar: null, $implicit: null }; private viewRef: any; constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<NgVarContext> ) {} // Handle the main value input (the expression before "as") @Input() set ngVar(value: any) { this.context.ngVar = value; this.context.$implicit = value; // Update the alias property if one exists const aliasKey = Object.keys(this.context).find(key => key !== 'ngVar' && key !== '$implicit'); if (aliasKey) { this.context[aliasKey] = value; } this.updateView(); } // Handle the alias from the "as" syntax @Input() set ngVarAs(alias: string) { // Clean up old alias properties Object.keys(this.context).forEach(key => { if (key !== 'ngVar' && key !== '$implicit') { delete this.context[key]; } }); // Add the new alias pointing to the current value if (alias) { this.context[alias] = this.context.ngVar; } this.updateView(); } private updateView() { if (!this.viewRef) { // Create the embedded view if it doesn't exist this.viewRef = this.viewContainerRef.createEmbeddedView(this.templateRef, this.context); } else { // Trigger change detection to update the view with new values this.viewRef.markForCheck(); } } }
Why This Fixes Your Loop Issue
- Proper Context Management: Each loop iteration gets its own instance of the directive, with a unique context that holds the correct value for that iteration.
- Change Detection: The
updateViewmethod ensures that whenever the input value or alias changes (like when the loop moves to the next client), the view is refreshed to reflect the new value. - Alias Support: The
ngVarAsinput handles the "as" syntax correctly, binding your alias (likeclientName) directly to the context so it's accessible in the template.
How to Use It
First, declare this directive in your Angular module's declarations array. Then use it in your loop like this:
<div *ngFor="let client of clients"> <div class="row" *ngVar="client.clientName as clientName"> {{ clientName }} <!-- This will correctly show each client's name in the loop --> </div> </div>
This implementation will keep your variable values intact across loop iterations and update them properly as the loop progresses.
内容的提问来源于stack exchange,提问作者Demodave
相关产品推荐
相关产品推荐

