Angular2 * ngIf隐藏模板中Div的内容

时间:2017-05-08 15:59:05

标签: angular typescript

我在第一个Angular2项目上处理表单,我似乎无法让*ngIf隐藏模板中的div。

这是我的组件文件:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Address } from './signup'

@Component({
  selector: 'address-area',
  styles: [],
  template: `
    <form name='addressForm' novalidate>

  <label> Get The Report via Standard Mail:</label>
  <input name='needAddress' class='checkbox' type='checkbox' [(ngModel)]='address.need' />
  <div *ngIf='isNeeded()'>
    <input name='add1' class='text' type='text' placeholder='Address Line 1' [(ngModel)]='address.add1' />
    <input name='add2' class='text' type='text' placeholder='Address Line 2' [(ngModel)]='address.add2' />
    <input name='city' class='text' type='text' placeholder='City' [(ngModel)]='address.city' />
    <input name='state' class='text' type='text' placeholder='State' [(ngModel)]='address.state' />
    <input name='zip' class='text' type='text' placeholder='Zip' [(ngModel)]='address.zip' />
    <input name='country' class='text' type='text' placeholder='Country' [(ngModel)]='address.country' />
  </div>
</form>
  `
})
export class AddressComponent {
  address: Address = new Address(false);
  isNeeded = function(){
    this.address.need == true;
  }
}

仅供参考,这是类对象。

export class Address{
  need: boolean;
  add1: string;
  add2: string;
  city: string;
  state: string;
  zip: string;
  country: string;
  constructor(public n: boolean){
    this.need = n;
  }
}

1 个答案:

答案 0 :(得分:0)

isNeeded()需要返回ngIf的值才能进行评估。

export class AddressComponent {
  address: Address = new Address(false);
  isNeeded = function(){
    return this.address.need == true; // returns the value
  }
}

此外,如果您只想显示/隐藏元素,请使用样式绑定而不是ngIf,因为如果传递的表达式求值为ngIf 从DOM中移除元素false如果多次发生则效率不高。您使用样式绑定来显示/隐藏这样的元素

<div [style.display]='isNeeded() ? "block" : "none"'>
    <input name='add1' class='text' type='text' placeholder='Address Line 1' [(ngModel)]='address.add1' />
    <input name='add2' class='text' type='text' placeholder='Address Line 2' [(ngModel)]='address.add2' />
    <input name='city' class='text' type='text' placeholder='City' [(ngModel)]='address.city' />
    <input name='state' class='text' type='text' placeholder='State' [(ngModel)]='address.state' />
    <input name='zip' class='text' type='text' placeholder='Zip' [(ngModel)]='address.zip' />
    <input name='country' class='text' type='text' placeholder='Country' [(ngModel)]='address.country' />
  </div>

现在,您的div仍将在DOM中,每次表达式更改值时,angular justs都会切换其style.display属性