Manush
Manush

Reputation: 1942

Why changing value in component file(.ts) not rendering in template file(.html)

I tried to change a value in component file, but the current and updated value not rendered in the template file. Here is my Code.

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

@Component({
  selector: 'cr-content-upload',
  templateUrl: './app/template.html'
})
export class ContentUploadComponent {
  constructor( ) { }  

  toggleContent:boolean = false; 
  updateContent(data:any) {
      if(data == "streaming") {
         this.toggleContent = true;
         console.log(this.toggleContent);
      }
  }
  ngOnInit() {

  } 
}

and here is my template.html

<a href="javascript:void(0)" (click)="updateContent('streaming')">
<div *ngIf="toggleContent">
    This is sample Content
</div>

Note: When the value is logged to console, it prints the updated value. But, the updated value doesn't get rendered into template.html file. And also i get this issue in many occasion. So, kindly provide solution and also reason for the issue.

Upvotes: 0

Views: 1269

Answers (1)

AVJT82
AVJT82

Reputation: 73357

Your code looks fine, but if your template isn't detecting the changes, you could try and use ChangeDetectorRef.

import {ChangeDetectorRef} from '@angular/core'

and in your component inject it to your constructor and use it after setting your boolean to true.

constructor(private changeDetectorRef: ChangeDetectorRef)

updateContent(data:any) {
  if(data == "streaming") {
     this.toggleContent = true;
     this.changeDetectorRef.detectChanges();
   }
}

Upvotes: 1

Related Questions