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

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

问题描述

在angular1中,我们根据ng-if条件调用函数ng-init.以下代码表示 If first div 与 date && 匹配时间然后它会检查第二个条件,检查或未检查.如果选中则自动调用 play() 函数,如果未选中则调用 pause 函数.

<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>

我想通过 angular2 打字稿转换此代码.有没有办法根据angular 2中的条件自动调用函数?

解决方案

Angular2 中没有 ng-init.不过,您可以自己轻松创建这样的指令.

import { Directive, Input } from '@angular/core';@指示({选择器:'[ngInit]'})导出类 NgInit {@Input() ngInit;ngOnInit() {如果(this.ngInit){this.ngInit();}}}

然后像

一样使用它

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

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>

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

解决方案

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();
        }
    }
}

and then use it like

<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天全站免登陆