将Angular 1转换为Angular 2 ngInit函数 [英] Converting Angular 1 to Angular 2 ngInit function

查看:107
本文介绍了将Angular 1转换为Angular 2 ngInit函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular1中,我们根据ng-if条件调用函数ng-init。以下代码表示如果第一个div匹配日期和&&然后它将检查第二个条件,检查或未检查。如果选中则会自动调用play()函数,如果没有检查则调用pause函数。

In angular1, we call the function ng-init based on ng-if condition. The following code represents If first div match with date && time then it will check the second condition, checked or not checked. If checked then it's automatically call play() function and if it's not check then call the pause function.

<div ng-if="ramadan.date === date && ramadan.time === clock">
  <div ng-if="ramadan.checked" ng-init="play()"></div>
  <div ng-if="!ramadan.checked" ng-init="pause()"></div>
</div>

我想用angular2 typescript转换这段代码。有没有办法根据角度2中的条件自动调用函数?

I want to convert this code by angular2 typescript. Is there any way to automatically call the function based on condition in angular 2?

推荐答案

没有 Angular2中的ng-init 。你可以自己轻松地创建这样的指令。

There is no ng-init in Angular2. You can easily create such a directive yourself though.

import { Directive, Input } from '@angular/core';

@Directive({
    selector: '[ngInit]'
})
export class NgInit {
    @Input() ngInit;
    ngOnInit() {
        if (this.ngInit) {
            this.ngInit();
        }
    }
}

然后使用它像

<div *ngIf="ramadan.date === date && ramadan.time === clock">
  <div *ngIf="ramadan.checked" [ngInit]="play"></div>
  <div *ngIf="!ramadan.checked" [ngInit]="pause"></div>
</div>

这篇关于将Angular 1转换为Angular 2 ngInit函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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