Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

typescript - How to achieve different output with the same selector in angular

child component.html:

<div *ngIf="variable1===true">
  Container 1
</div>

<div *ngIf="variable2===true">
   Container 2
</div>

child component.ts

@Input() variable1: boolean;
@Input() variable2: boolean;

appcomponent.html

<button (click)="Activate_variable1">Activate Variable1</button>
<button (click)="Activate variable2">Activate Variable2</button>
<child-component [variable1]="variable1" [variable2]="variable2"></child-component>
<child-component [variable1]="variable1" [variable2]="varibale2"></child-component>

appcomponent.ts

variable1 = false;
variable2 = false;

Activate_variable1(){
this.variable1 = true;
this.variable2 = false;
}

Actiavate_variable2(){
this.variable2 = true;
this.variable1 = false;
}

So, here I may get output as container 1 twice or container 2 twice but what I'm looking here is Container 1 and Container 2 as output (one selector should give container 1 as output and the other selector should give container 2 as output). How can I achieve this?

Thanks in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quick fix for the above example (i.e. you have only two child components, and your variables are of boolean type) would be reversing values for the variables

<button (click)="Activate_variable1">Activate Variable1</button>
<button (click)="Activate variable2">Activate Variable2</button>
<child-component [variable1]="variable1" [variable2]="variable2"></child-component>
<child-component [variable1]="!variable1" [variable2]="!variable2"></child-component>

Also, you can simplify your code for the child component by removing === comparison if the only possible values for that variable are true and false, i.e.:

<div *ngIf="variable1">
  Container 1
</div>

<div *ngIf="variable2">
   Container 2
</div>

Does it answer your question?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...