简体   繁体   English

为什么更改组件文件(.ts)中的值而不呈现在模板文件(.html)中

[英]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 这是我的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. 但是,更新后的值不会呈现到template.html文件中。 And also i get this issue in many occasion. 而且我在很多场合都遇到了这个问题。 So, kindly provide solution and also reason for the issue. 因此,请提供解决方案以及问题的原因。

Your code looks fine, but if your template isn't detecting the changes, you could try and use ChangeDetectorRef . 您的代码看起来不错,但是如果您的模板没有检测到更改,则可以尝试使用ChangeDetectorRef

import {ChangeDetectorRef} from '@angular/core'

and in your component inject it to your constructor and use it after setting your boolean to true . 并在您的组件中将其注入到构造函数中,并在将boolean设置为true之后使用它。

constructor(private changeDetectorRef: ChangeDetectorRef)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将index.html页面中的值传递给angular4中的component.ts文件 - How to pass a value from index.html page to component.ts file in angular 4 我如何获取HTML标记内的值并将其绑定到aurelia中的ts(组件文件) - How can i get the value which is inside the HTML tag and bind it to the ts(component file) in aurelia 在来自不同文件的 Web 组件槽中渲染 HTML5 模板 - Rendering HTML5 template in web-component slot from different file 离子2从ts文件引用html文件中的值? - Ionic 2 reference a value in html file from ts file? 使用html文件作为角度2中组件的模板 - Using html file as template for component in angular 2 如何将输入的数据从一个html文件移动到其ts文件,然后再移动到另一个组件文件? - How to move the entered data from one html file to its ts file and then to another component file? 参考 HTML 中的 SCSS 变量值或 Angular 中的 TS 文件 - Refer SCSS variable value in HTML or TS file in Angular angular 形式值 {} 在 ts 文件中是 null 但在 html 中有效 - angular form value {} is null in ts file but works in html 从HTML文件中的TypeScript(.ts)获取值。 - Get value from TypeScript (.ts) in HTML file. 将Vuejs单文件组件中的模板导入为外部HTML文件 - Import template in Vuejs single file component as an external HTML file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM