变量和插值

所谓 “插值” 是指将表达式嵌入到标记文本中。 默认情况下,插值会用双花括号 {{ 和 }} 作为分隔符。

变量语法:修饰符 变量名: 数据类型 = xxx;,其中修饰符和数据类型可以省略,数据类型的具体内容查看参考来源

公共,私有与受保护的修饰符

此处的解释仅适用于 Angular 组件当中,更多解释查看参考来源

  • 公共的 public:在类的内外都可以使用;
  • 私有的 private:只有在类当中才可以使用;
  • 受保护的 protected:只有在当前类和它的子类中可以使用。

我们需要先在 news 组件(src/app/components/news/news.component.ts)中定义变量:

  1. import { Component, OnInit } from '@angular/core';
  2. @Component({
  3. selector: 'app-news',
  4. templateUrl: './news.component.html',
  5. styleUrls: ['./news.component.scss']
  6. })
  7. export class NewsComponent implements OnInit {
  8. public title: string = '新闻页';
  9. constructor() { }
  10. ngOnInit(): void {
  11. }
  12. }

然后在 new 组件页面(src/app/components/news/news.component.html)中插值:

  1. <p>news works!</p>
  2. <app-header></app-header>
  3. <h1>{{title}}</h1>

image.png

参考来源

[

](https://www.tslang.cn/docs/handbook/basic-types.html)