将Angular 1转换为Angular 2 ngInit函数

Afr*_*min 2 javascript angularjs angular

在angular1中,我们根据ng-if条件调用函数ng-init.以下代码表示如果第一个div匹配日期&&时间,则它将检查第二个条件,已选中或未选中.如果选中则会自动调用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>
</div>
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 11

ng-initAngular2中没有.您可以自己轻松地创建这样的指令.

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

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

然后像使用它一样

<div *ngIf="ramadan.date === date && ramadan.time === clock">
  <div *ngIf="ramadan.checked" [ngInit]="play"></div>
  <div *ngIf="!ramadan.checked" [ngInit]="pause"></div>
</div>
Run Code Online (Sandbox Code Playgroud)


Afr*_*min 6

工作代码,

自定义指令:

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

@Directive({ selector: '[myCondition]' })

export class ngInitDirective {
  constructor() { }


  @Input() set myCondition(condition: boolean) {
    if (!condition) {
      console.log("hello")
    } else {
      console.log("hi")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在模板中:

<ion-label *ngIf="setting1.date === current_date && setting1.time === current_time">
          <div *myCondition="setting1.checked === condition" >Play</div>
          <div *myCondition="!setting1.checked === !condition">pause</div>
      </ion-label>
Run Code Online (Sandbox Code Playgroud)