Home > Software engineering >  I need to have a 'container' template that has to show MyComponent upon certain condition
I need to have a 'container' template that has to show MyComponent upon certain condition

Time:08-07

container.html

<div ngIf="externalCondition"> <!--Initially this is false. Later became true --!>
  <my-component #MyComponentElem > </my-component>
  <button [disabled]= "!myComponentElemRef.myDetailsForm.valid" (click)="myComponentElemRef.AFunctionInsideComponent()"> </button>
  
</div>

container.ts

@Component({
    selector: 'my-component',
    templateUrl: './comm-roleplay-end2end.html',
    styleUrls: ['./comm-roleplay-end2end.scss'] 
})
export class  Container {
 @ViewChild('MyComponentElem', { static: true }) private myComponentElemRef: MyComponent;

}

mycomponent.ts

@Component({
    selector: 'my-component',
    templateUrl: './my-component.html',
    styleUrls: ['./my-component.scss'] 
})

export class MyComponent {

 public externalCondition:Boolean = false;
 public myDetailsForm: FormGroup;
 constructor()
  {
  //my form builder
  }
 
 //
 public AFunctionInsideComponent()
 {
 }

}

Based on myDetailsForm.valid, I need to turn on something in my container.

Issue is that myComponentElemRef is 'undefined' because the element is not created initially. It is visible only after 'externalCondition' becomes true. Upon button click, I need the FormGroup of MyContent to be visible. But it gets stuck in script error due to

TypeError: reading undefined (myComponentElemRef)

Please suggest the best mechanism to handle the situation

CodePudding user response:

try using [hidden] instead of ngIf, that way the component is created but not visible

  • Related