我有以下模板:
<div>
<span>{{aVariable}}</span>
</div>
并希望以:
<div "let a = aVariable">
<span>{{a}}</span>
</div>
有办法吗?
我有以下模板:
<div>
<span>{{aVariable}}</span>
</div>
并希望以:
<div "let a = aVariable">
<span>{{a}}</span>
</div>
有办法吗?
当前回答
我是https://www.npmjs.com/package/ng-let的作者
将数据作为局部变量共享到html组件模板的结构指令。
源代码:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
interface NgLetContext<T> {
ngLet: T;
$implicit: T;
}
@Directive({
// tslint:disable-next-line: directive-selector
selector: '[ngLet]'
})
export class NgLetDirective<T> {
private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
private hasView: boolean = false;
// eslint-disable-next-line no-unused-vars
constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }
@Input()
set ngLet(value: T) {
this.context.$implicit = this.context.ngLet = value;
if (!this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef, this.context);
this.hasView = true;
}
}
/** @internal */
public static ngLetUseIfTypeGuard: void;
/**
* Assert the correct type of the expression bound to the `NgLet` input within the template.
*
* The presence of this static field is a signal to the Ivy template type check compiler that
* when the `NgLet` structural directive renders its template, the type of the expression bound
* to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
* narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
*/
static ngTemplateGuard_ngLet: 'binding';
/**
* Asserts the correct type of the context for the template that `NgLet` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgLet` structural directive renders its template with a specific context type.
*/
static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
return true;
}
}
用法:
import { Component } from '@angular/core';
import { defer, Observable, timer } from 'rxjs';
@Component({
selector: 'app-root',
template: `
<ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
<div>
1: {{ time }}
</div>
<div>
2: {{ time }}
</div>
</ng-container>
`,
})
export class AppComponent {
timer$: Observable<number> = defer(() => timer(3000, 1000));
}
其他回答
更新3
问题https://github.com/angular/angular/issues/2451在Angular 4.0.0中已修复
另请参阅
https://github.com/angular/angular/pull/13297 https://github.com/angular/angular/commit/b4db73d https://github.com/angular/angular/issues/13061
更新2
这是不支持的。
有模板变量,但不支持分配任意值。它们只能用于引用它们应用的元素,导出指令或组件的名称,以及ngFor等结构指令的作用域变量,
参见https://github.com/angular/angular/issues/2451
更新1
@Directive({
selector: '[var]',
exportAs: 'var'
})
class VarDirective {
@Input() var:any;
}
然后像这样初始化
<div #aVariable="var" var="abc"></div>
or
<div #aVariable="var" [var]="'abc'"></div>
然后用这个变量
<div>{{aVariable.var}}</div>
(未测试)
# variable创建对VarDirective的引用(exportAs: 'var') var="abc"实例化VarDirective,并将字符串值"abc"传递给它的值输入。 aVariable。Var读取分配给Var指令Var输入的值。
如果你想要得到函数的响应并将其设置为变量,你可以像下面这样在模板中使用它,使用ng-container来避免修改模板。
<ng-container *ngIf="methodName(parameters) as respObject">
{{respObject.name}}
</ng-container>
组件中的方法可以是
methodName(parameters: any): any {
return {name: 'Test name'};
}
一个简单的解决方案可以满足我的需求:
<ng-container *ngIf="lineItem.productType as variable">
{{variable}}
</ng-container>
OR
<ng-container *ngIf="'ANY VALUE' as variable">
{{variable}}
</ng-container>
我使用的是Angular版本:12。这似乎也适用于其他版本。
我喜欢创建一个指令来做这件事的方法(很好的调用@yurzui)。
最后我在Medium上找到了一篇文章,Angular的“let”指令很好地解释了这个问题,并提出了一个自定义的let指令,它在我的用例中工作得很好,代码更改很少。
以下是要点(在发布时)和我的修改:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'
interface LetContext <T> {
appLet: T | null
}
@Directive({
selector: '[appLet]',
})
export class LetDirective <T> {
private _context: LetContext <T> = { appLet: null }
constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
_viewContainer.createEmbeddedView(_templateRef, this._context)
}
@Input()
set appLet(value: T) {
this._context.appLet = value
}
}
我的主要改变是:
将前缀从'ng'更改为'app'(你应该使用你的应用程序的自定义前缀是什么) 将appLet: T更改为appLet: T | null
不知道为什么Angular团队还没有发布一个官方的ngLet指令。
原始源代码归功于@AustinMatherne
你可以使用Angular 2中的template元素或Angular 4+中的ng-template在html代码中声明变量。
模板有一个上下文对象,它的属性可以使用let绑定语法分配给变量。注意,您必须为模板指定一个出口,但它可以是对模板本身的引用。
<ng-template #selfie [ngTemplateOutlet]="selfie"
let-a="aVariable" [ngTemplateOutletContext]="{ aVariable: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
<!-- Output
<div>
<span>123</span>
</div>
-->
您可以通过使用context对象的$implicit属性而不是自定义属性来减少代码量。
<ng-template #t [ngTemplateOutlet]="t"
let-a [ngTemplateOutletContext]="{ $implicit: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
上下文对象可以是文字对象或任何其他绑定表达式。其他有效例子:
<!-- Use arbitrary binding expressions -->
<ng-template let-sum [ngTemplateOutletContext]="{ $implicit: 1 + 1 }">
<!-- Use pipes -->
<ng-template let-formatPi [ngTemplateOutletContext]="{ $implicit: 3.141592 | number:'3.1-5' }">
<!-- Use the result of a public method of your component -->
<ng-template let-root [ngTemplateOutletContext]="{ $implicit: sqrt(2116) }">
<!--
You can create an alias for a public property of your component:
anotherVariable: number = 123;
-->
<ng-template let-aliased [ngTemplateOutletContext]="{ $implicit: anotherVariable }">
<!--
The entire context object can be bound from a public property:
ctx: { first: number, second: string } = { first: 123, second: "etc" }
-->
<ng-template let-a="first" let-b="second" [ngTemplateOutletContext]="ctx">