简体   繁体   中英

How to append child component into parent component conditionally?

I have two components, parent and register component.

ParentComponent.html looks like:

<div class="tab-content">
    <div class="tab-pane" id="signup" (click)="getChild()">
        <register></register>  --//register component
    </div>
 </div>

register.component.ts looks like:

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'register',
    templateUrl: '../templates/register.html'
})
export class RegisterComponent implements OnInit { 
   ngOnInit() {
       this.registerService.getRoleList()
        .subscribe(res => {
            if(res.data){
                this.instRoleList = res.data.roleList;
            }
        });

     /* ngOnInit calls a service from which data is received and certain 
        conditions are met. I want this service to go only when getDetails() is called and <register> should get append to <div id="signup>

*/
   }
}

register.html code snippet looks like: ( it depends on the data received from register service data "")

<div class="form-group group" *ngIf="instRoleList">
 </div>

So, I want that on click of getChild(), register component gets appended to <div id="signup">

How to achieve this?

<div class="tab-pane" id="signup" (click)="getChild()">
          <!-- register component to append here on getChild() click -->
</div>

I have already used below code but didn't work.

$('#signup').append('<register></register>')

This could easily be archieved with the ngIf directive:

<div class="tab-content">
         <div class="tab-pane active" id="signin">
            <!-- other code -->
        </div>
        <div class="tab-pane" id="signup" (click)="getChild()">
            <register *ngIf="condition"></register>  --//register component
        </div>
     </div>

@Component({
    selector: 'register',
    templateUrl: '../templates/register.html'
})
export class ParentComponent { 
   condition: boolean = false;
   getChild(){
      this.condition = !this.condition;
   }
}

This click event will work as a toggle function with this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM