最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to load component conditionally in angular on button click - Stack Overflow

programmeradmin0浏览0评论

I'm very new to Angular.

I want to load a child ponent conditionally within a ponent by clicking button. On button click, it should re-render the respective child ponent.

HTML code

<div class="tab">
  <button class="tablinks" (click)="onTabClick('0')">Transmit</button>
  <button class="tablinks" (click)="onTabClick('1')">Published</button>
  <button class="tablinks" (click)="onTabClick('2')">Bulk Transmit</button>
</div>
<div>
  <app-sports  *ngIf="tabIndex === 0"></app-sports>
  <app-movies  *ngIf="tabIndex === 2"></app-movies>
</div>

TS file

tabIndex = 2 ;


  onTabClick(index){
        this.tabIndex = index;
   }

I'm very new to Angular.

I want to load a child ponent conditionally within a ponent by clicking button. On button click, it should re-render the respective child ponent.

HTML code

<div class="tab">
  <button class="tablinks" (click)="onTabClick('0')">Transmit</button>
  <button class="tablinks" (click)="onTabClick('1')">Published</button>
  <button class="tablinks" (click)="onTabClick('2')">Bulk Transmit</button>
</div>
<div>
  <app-sports  *ngIf="tabIndex === 0"></app-sports>
  <app-movies  *ngIf="tabIndex === 2"></app-movies>
</div>

TS file

tabIndex = 2 ;


  onTabClick(index){
        this.tabIndex = index;
   }
Share Improve this question edited Jun 14, 2019 at 10:08 Shivam Mishra 1,8561 gold badge13 silver badges16 bronze badges asked Jun 14, 2019 at 9:50 RamsRams 2,1897 gold badges33 silver badges62 bronze badges 1
  • 3 You are passing string('0') and checking with a number 0, either make === to == or pass number on both sides. – Puneet Uppal Commented Jun 14, 2019 at 9:54
Add a ment  | 

3 Answers 3

Reset to default 5

you have passed string as argument but checking numbers in tab. you can check on stackblitz link:

check stackblitz link here

<div class="tab">
  <button class="tablinks" (click)="onTabClick(0)">Transmit</button>
  <button class="tablinks" (click)="onTabClick(1)">Published</button>
  <button class="tablinks" (click)="onTabClick(2)">Bulk Transmit</button>
</div>
<div>
  <app-sports  *ngIf="tabIndex === 0"></app-sports>
  <app-movies  *ngIf="tabIndex === 2"></app-movies>
</div>

you are passing parameters 0,1,2 like strings and checking condition with === it' also checking type (means sting or number)

Possible solutions:

  1. place == instead of ===

  2. change argumens '1' to 1, '2' to 2

You are passing 0,1,2 as string in the onTabClick(), whereas in the .ts file you have tabIndex as integer.

发布评论

评论列表(0)

  1. 暂无评论