【问题标题】:Angular variable in component not rendering in template组件中的角度变量未在模板中呈现
【发布时间】:2020-07-18 10:59:39
【问题描述】:

回答:我使用的是 title: 'myTitle' 而不是 title = 'myTitle' ;(

我刚刚生成了一个带有一个新组件的新 Angular 应用程序。 问题是当我在类组件中初始化一个变量并尝试使用 {{}} 在模板中输出它时,它没有显示变量的值。

在主 App-Root 组件中,它的编写方式与我的代码一样,但它可以正常工作:(

content.component.ts

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

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

export class ContentComponent {
  title: 'Content'
}

content.component.html

<h3>{{title}}</h3>

【问题讨论】:

  • 向我们展示代码
  • 我们需要看一些代码:)
  • 对不起,我添加了代码

标签: node.js angular templates components


【解决方案1】:

这就是你应该如何绑定值:

component.ts

public title:any = 'Content';

component.html

<h1> {{title}} </h1>

这是一个工作示例:demo

【讨论】:

    【解决方案2】:

    如下使用角度变量 标题:字符串=“内容” 例如 试试这个,我创建了一个示例 MyComponent 类,如下所示。

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.css']
    })
    export class MyComponentComponent implements OnInit {
    
      private myVariable:string="Hello World"
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    

    我的组件.component.html

    <p>
    {{myVariable}}
    </p>
    

    确保在 app.component.html 中添加上面的组件,它是下面的引导组件

    <app-my-component></app-my-component>
    

    也在 app.module 中,如下声明部分

     declarations: [
        AppComponent,
        TopBarComponent,
        ProductListComponent,
        MyComponentComponent
      ],
      bootstrap: [ AppComponent ]
    

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 1970-01-01
      • 2019-04-09
      • 2018-12-16
      • 2019-06-15
      • 1970-01-01
      • 2017-11-08
      • 2020-12-02
      • 2022-10-26
      相关资源
      最近更新 更多