Angular2+学习第3篇 基本知识-组件


一、插值表达式

基本用法与ng1一样。

可以使用 Angular 内置的 json 管道,来显示对象信息,管道用来格式化数据

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

@Component({
  selector: 'app-root',
  template: `
    

大家好我是来自{{address.province}}省{{address.city}}市的{{name}}

{{address | json}}

`, styleUrls: ['./app.component.css'] }) export class AppComponent { name = 'Angular'; address = { province:'河北', city: '唐山' }; }

二、组件

在 Angular 中,我们可以通过 @Component 装饰器和自定义组件类来创建自定义组件。

  • 1.      Angular 中,我们可以使用 @Component 装饰器来定义组件的元信息
@Component({
  selector: 'my-app', // 用于定义组件在HTML代码中匹配的标签
  template: `

Hello {{name}}

`, // 定义组件内嵌视图 })
  • 2.      定义组件类
export class AppComponent  {
  name = 'Angular';
}
  • 3.      定义数据接口

在 TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。

interface Person {
  name: string;
  age: number;
}

let semlinker: Person = {
  name: 'semlinker',
  age: 31
};

一、自定义组件示例:创建 UserComponent 组件

生成组件的命令:

ng g component **

创建 UserComponent 组件:ng g component user

angular-cli工具自动为我们生成的相关基本文件和代码