Home > front end >  How can i load two childs components conditionally on Angular 8
How can i load two childs components conditionally on Angular 8

Time:10-27

Consider the following hierarchy:

<app-component>
    <university-component></university-component>
    <highSchool-component></highSchool-component>
</app-component>

And a dialog component (dialog-component) that display at the opening app-component contains 2 choices ( university and high School :

<form nz-form [nzLayout]="'inline'" [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <h3> Please select your academic level </h3>
            <nz-form-control [nzErrorTip]="getErrorTip('studentLevel')">
              <nz-radio-group [(ngModel)]="radioValue" formControlName="studentLevel" nzButtonStyle="solid" nzSize="small">

                  <input type="radio" name="radio3" id="university" (change)="setRouter(2)">
                      <label class="universite-label four col" nzValue="universite" for="universite">University</label>
                  <input type="radio" name="radio3" id="highSchool" (change)="setRouter(1)">
                      <label class="lycee-label four col" nzValue="lycee" for="lycee" >High School</label>

              </nz-radio-group>
            </nz-form-control>
            
       <div>
       <label nzType="flex" nzJustify="center" nzAlign="middle" nz-radio-button (click)="changeRoute()" mat-dialog-close >GO</label>
       </div>

</form>

How Can I if I chose University the app-component load university-component and if I chose high School the the app-component load highSchool-component

CodePudding user response:

I think you already have radioValue bound to ngModel, so you can do the following, assuming that AppComponent has access to radioValue

<app-component>
  <university-component *ngIf="radioValue === 'universityComponentVal'"> </university-compnent>
  <high-school-component *ngIf="radioValue === 'highSchoolVal'"></high-school-component>
</app-component>

If the number of conditionally rendered components increase, you may want to use ngSwitch and ngSwtichCase https://angular.io/api/common/NgSwitchCase

CodePudding user response:

Thank you all for your answers,

I found the solution. I created a service "level.service.ts" :

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LevelService {

  isUniversity: boolean = true;

  constructor() { }

  highScool() {
    this.isUniversity = false;
  }

  universite() {
    this.isUniversity = true;
  } 
} 

and in app-component :

<app-component>
    <university-component *ngIf="levelService.isUniversity"></university-component>
    <highSchool-component *ngIf="!levelService.isUniversity"></highSchool-component>
</app-component>

and I added in dialog.component.html two (click) :

<form nz-form [nzLayout]="'inline'" [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <h3> Please select your academic level </h3>
            <nz-form-control [nzErrorTip]="getErrorTip('studentLevel')">
              <nz-radio-group [(ngModel)]="radioValue" formControlName="studentLevel" nzButtonStyle="solid" nzSize="small">

                  <input type="radio" name="radio3" id="university" (change)="setRouter(2)">
                      <label class="universite-label four col" nzValue="universite" for="universite" (click)="university()">University</label>
                  <input type="radio" name="radio3" id="highSchool" (change)="setRouter(1)">
                      <label class="lycee-label four col" nzValue="lycee" for="lycee" (click)="highSchool()">High School</label>

              </nz-radio-group>
            </nz-form-control>
            
       <div>
       <label nzType="flex" nzJustify="center" nzAlign="middle" nz-radio-button (click)="changeRoute()" mat-dialog-close >GO</label>
       </div>

</form>

and in dialog.component.ts :

import { Component} from '@angular/core';
import { UniversityService } from 'src/app/services/university.service';
// others import

@Component({
  selector: 'app-dialog-video',
  templateUrl: './dialog-video.component.html',
  styleUrls: ['./dialog-video.component.css']
})

export class DialogVideoComponent implements OnInit {

  @Input() radioValue = 'college'

  isUniversity: string = 'universite';

  // constructor() { } 
 
 // other logics

  ngOnInit() {
    // this.universityService.isUniversity = this.radioValue;
    this.universityService.collegeLycee(),
    this.universityService.universite()
  }

  highSchool() {
    this.universityService.collegeLycee();
  }

  university() {
    this.universityService.universite();
  }

}

CodePudding user response:

I believe ngIf is the easy way out here, instead I would recommend using routes, that is unless there are shared variables with the parent component. This would also allow for deep linking in the future so that your users may avoid needing to select a value every time.

export const appRoutes: Routes = [
  ... Any other routes you have
  {
    path: 'university',
    component: UniversityComponent,
  },
  {
    path: 'highSchool',
    component: HighSchoolComponent
  }
};

@NgModule({
  imports: [
    ...
    RouterModule.forRoot(appRoutes)
  ]
})
export class AppModule {}

And you can either go to that route from the html using the routerLink directive from angular, or from the current function being called on the form.

@Component({
  ...
})
export class AppComponent {
  radioValue: 'university' | 'highSchool';
 
  constructor(private router: Router) {}

  changeRoute() {
    this.router.navigate([this.radioValue]);
  }
}

It looks like you are also uning formControlName with ngModel, this can cause errors. the above method is using the ngModel value, you can use the form value by accessing your form value just the same.

  • Related