Angular 2中的angular的ng-init替代方案 [英] angular's ng-init alternative in Angular 2

查看:189
本文介绍了Angular 2中的angular的ng-init替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2中ng-init="myText='Hello World!'"在模板中而不是在组件中添加的替代方法是什么

What is the alternative of ng-init="myText='Hello World!'" in Angular 2 to add in the template, not in the component

 <div ng-app="" ng-init="myText='Hello World!'">

Angular 2中的替代项

the alternative in Angular 2

推荐答案

您可以使用指令

@Directive({
  selector: 'ngInit',
  exportAs: 'ngInit'
}) 
export class NgInit {
  @Input() values: any = {};

  @Input() ngInit;
  ngOnInit() {
    if(this.ngInit) { this.ngInit(); }
  }  
}

您可以使用它来传递要调用的函数

you can use it to pass a function to be called like

<div [ngInit]="doSomething"

或使值可用

<div ngInit [values]="{a: 'a', b: 'b'}" #ngInit="ngInit">
  <button (click)="clickHandler(ngInit.values.a)">click me</button>
</div>

  • ngInit添加指令
  • [values]="{a: 'a', b: 'b'}"设置一些初始值
  • #ngInit="ngInit"创建参考以供以后使用
  • ngInit.values.a从创建的引用中读取a值.
    • ngInit addes the directive
    • [values]="{a: 'a', b: 'b'}" sets some initial values
    • #ngInit="ngInit" creates a reference for later use
    • ngInit.values.a reads the a value from the created reference.
    • 另请参见将Angular 1转换为Angular 2 ngInit功能

      这篇关于Angular 2中的angular的ng-init替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆