Sha*_*mil 26 typescript angular
ng-init="myText='Hello World!'"
Angular 2中的替代方法是在模板中添加,而不是在组件中添加
<div ng-app="" ng-init="myText='Hello World!'">
Run Code Online (Sandbox Code Playgroud)
Angular 2中的替代方案
Gün*_*uer 21
您可以使用指令
@Directive({
selector: 'ngInit',
exportAs: 'ngInit'
})
export class NgInit {
@Input() values: any = {};
@Input() ngInit;
ngOnInit() {
if(this.ngInit) { this.ngInit(); }
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用它来传递一个被调用的函数
<div [ngInit]="doSomething"
Run Code Online (Sandbox Code Playgroud)
或者提供价值
<div ngInit [values]="{a: 'a', b: 'b'}" #ngInit="ngInit">
<button (click)="clickHandler(ngInit.values.a)">click me</button>
</div>
Run Code Online (Sandbox Code Playgroud)
ngInit
加入指令[values]="{a: 'a', b: 'b'}"
设置一些初始值#ngInit="ngInit"
创建一个供以后使用的参考ngInit.values.a
a
从创建的引用中读取值.另请参见将Angular 1转换为Angular 2 ngInit函数
另一种方法是使用@Output装饰器和EventEmitter:
import {Directive, OnInit, Output, EventEmitter} from '@angular/core';
@Directive({
selector: '[ngInit]'
})
export class NgInitDirective implements OnInit {
@Output()
ngInit: EventEmitter<any> = new EventEmitter();
ngOnInit() {
this.ngInit.emit();
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
<div *ngIf="condition" (ngInit)="initialize()"> ... </div>
Run Code Online (Sandbox Code Playgroud)
@Directive({
selector: '[ngxInit]',
})
export class NgxInitDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) {
}
@Input() set ngxInit(val: any) {
this.viewContainer.clear();
this.viewContainer.createEmbeddedView(this.templateRef, {ngxInit: val});
}
}
Run Code Online (Sandbox Code Playgroud)
值表达式通过微语法设置*ngxInit
和发布as
:
<div *ngxInit="3 * i + j as idx">{{idx}}</div>
Run Code Online (Sandbox Code Playgroud)
发布为https://www.npmjs.com/package/ngx-init
归档时间: |
|
查看次数: |
55999 次 |
最近记录: |