使用* ngIf Angular2隐藏/显示

时间:2017-01-20 20:42:19

标签: angular event-binding ngif

我想根据*ngIf条件值隐藏和显示两个元素。

默认情况下,我的wrap数据块是可见的,当我点击其中一个divs时,此wrap数据块应该会消失,并且只应在内部显示所选的div's内容我的span元素。 然后当我点击我的span元素时,它应该会消失,并且wrap阻止应该再次显示其所有默认内容。

为了实现我对两个元素都使用值为*ngIf的{​​{1}},期望我的函数以下列方式工作:

visability

这是我的代码:

wrap - visible;
span - hidden;

wrap - hidden;
span - visible;

@Component({
selector: 'my-app',
template: `
<div id="wrap" class="wrap" *ngIf="visability">
<div (click)="clicked($event)">
  <h2>Hello {{name}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{year}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{surname}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{country}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{cartoon}}</h2>
</div>

My Plunker

为什么我的功能不能以正确的方式工作?

2 个答案:

答案 0 :(得分:2)

我实际上改变了你的代码。对于第一个div,将visability设为true,对于第二个div设为false。更好地分开它们。然后它只是根据点击来切换布尔值,如下所示:

首先将可见性声明为变量,以便您可以使用this引用它,然后切换可见性。

  clicked(event) {
    this.visability = false;
    this.target = event.target.innerText;
  }

  showDivs(){
    this.visability = true;
    // span.visability = false; // remove this
    // wrap.visability = true;  // remove this
  }

和html相应:

<div id="wrap" class="wrap" *ngIf="visability">

<span id="span" (click)="showDivs()" *ngIf="!visability">{{target}}</span>

这是一个解决方案。

您的plunker

答案 1 :(得分:0)

我通过删除*ngIf作为我的第二个元素来解决它。我刚刚使用* ngIf =“显示”作为span

然后在构造函数中我设置了两个

visibility = true

shown = true

在函数内部,我将值切换到相反的位置,从而设法实现我想要的,但我不知道这是否是最好的方法。

@Component({
  selector: 'my-app',
  template: `
  <div id="wrap" class="wrap" *ngIf="visibility">
    <div (click)="clicked($event)">
      <h2>Hello {{name}}</h2>
    </div>
    <div (click)="clicked($event)">
      <h2>Hello {{year}}</h2>
    </div>
    <div (click)="clicked($event)">
      <h2>Hello {{surname}}</h2>
    </div>
    <div (click)="clicked($event)">
      <h2>Hello {{country}}</h2>
    </div>
    <div (click)="clicked($event)">
      <h2>Hello {{cartoon}}</h2>
    </div>
  </div>

  <div class="view">
    <span id="span" (click)="showDivs()" *ngIf="shown">{{target}}</span>
  </div>

  `,
})
export class App {
  name:string;
  year: string;
  surname: string;
  country: string;
  cartoon: string;
  element: any;
  target: any;

  clicked(event) {
     this.target = event.target.innerText;
     this.visibility = false;
     this.shown = true;
  }

  showDivs(){
     this.shown = false;
     this.visibility = true;
  }

  constructor() {
    this.visibility = true;
    this.shown = true;
    this.name = 'Angular2'
     this.year = '1989'
      this.surname = 'Connor'
       this.country = 'USA'
        this.cartoon = 'Tom & Jerry'
  }



}

Working Plunker

相关问题