angularangular-ng-if

Error "TS2339 Property 'elseblock' does not exist on type ''"


I'm trying to do an If Else with Angular:

<form [formGroup]="searchForm">
    <input formControlName="search"  placeholder="search show"/>
</form>
<div *ngIf="searchForm.value.search; else elseblock">
    search 
</div> 

<ng-template #elseblock>
   Listing
</ng-template>

But Typescript gives me an error:

error TS2339: Property 'elseblock' does not exist on type ''.

How can I fix it?

Here my TS file :

 export class ShowListComponent implements OnInit{
      searchForm :any;
      showsList:any = [];
    
      constructor(
        private showsService: ShowsService,
        private router : Router,
        private formBuilder: FormBuilder
      ) {
        this.searchForm = this.formBuilder.group({
          search: '',
        });
      }
    
      ngOnInit(): void {
        this.showsService.getShowsList()
          .subscribe(response => {
            this.showsList = response;
        })
      }
    
      goToShowDetail(show: any) {
        let title:string = show.name.replaceAll(' ','-').toLowerCase()
        this.router.navigate([this.router.url, show.id, title])
      }
    
      
    }

Solution

  • This is the right syntax for the ngIf else block in angular:

    <form [formGroup]="searchForm">
      <input formControlName="search"  placeholder="search show"/>
    </form>
    <div *ngIf="!searchForm.value.search; else elseblock">
      search
    </div>
    
    <ng-template #elseblock>
      Listing
    </ng-template>
    

    What was wrong?

    <form [formGroup]="searchForm">
      <input formControlName="search"  placeholder="search show"/>
    </form>
    <div *ngIf="searchForm.value.search else elseblock">. ====> You missed the semi colon here
        search 
    <div> ====> You should use a closing tag instead (</div>)
    
    <ng-template #elseblock>
       Listing
    <ng-template>  ====> Also here, it should be a closing tag (</ng-template>)
    

    Beside that, everything looks just fine.