angular组件及里面的模版

组件中声明数据

声明简单数据

  • 在相应组件的ts文件中的export中使用public(公有,默认是公有,可不写,在当前类,子类,外部都可以访问到);protected(保护类型,在当前类和子类中可以访问到);private(私有,在当前类中可以访问到)声明变量。如:
export class HeaderComponent implements OnInit {
  public title:string="我是头部组件"
  constructor() { }
}

然后在需要用到的html处{{变量名}}即可使用,最好指定数据类型,如此处指定了数据类型是string

声明对象类的数据

  • 方法和简单类的数据一样,只是数据类型为object或者any
export class HeaderComponent implements OnInit {
  public title:string="我是头部组件"
  public userinfor:object={
    name:'张三',
    age:20
  }
  constructor() { }
}

使用时在使用处{{userinfor.name}}即可访问到其中的数据进行渲染

声明数据但是不赋值

  • 也可声明数据(属性)但是不赋值,在方法中进行赋值,如
export class HeaderComponent implements OnInit {
  public title:string="我是头部组件"

  public userinfor:object={
    name:'张三',
    age:20
  }
  public msg:any;
  constructor() { 
    this.msg="给属性赋值"
    this.title="我是改变后的头部组件"
  }
}

在方法中进行赋值时使用this.数据名拿到数据进行赋值,此方法同样适用于已经赋值的数据

绑定属性

  • 绑定静态属性
    直接在其后写入

{{title}} {{userinfor.name}} {{msg}}

看看我的属性
  • 绑定动态属性,此时在需要的属性名上使用[]包裹起来,其等于的内容是在ts文件中声明的数据,属性的声明和数据是一样的
看看我的属性

绑定html

  • 在ts中声明
  public content:any="

我是一段内容

"
  • 在html中渲染
  • 在html模版中允许做简单的计算如
1+2={{1+2}}

显示的内容为1+2=3

angular中的数据循环(遍历)

  • 类似于vue中的v-for
  
  • {{item}}
    • 循环复杂数组,如下
     public cars:Array=[
        {
          title:"奥迪",
          list:[
            {
              title:'奥迪q1',
              price:'30万'
            },
            {
              title:'奥迪q2',
              price:'40万'
            },
            {
              title:'奥迪q3',
              price:'50万'
            }
          ]
        },
        {
          title:"宝马",
          list:[
            {
              title:'宝马q1',
              price:'50万'
            },
            {
              title:'宝马q2',
              price:'60万'
            },
            {
              title:'宝马q3',
              price:'70万'
            }
          ]
        }
      ]
    
    • 遍历时:
    {{key}}--{{item.title}}
    • {{car.title}}--{{car.price}}

    即可,注意里面的let key=index;得到索引

    你可能感兴趣的:(angular组件及里面的模版)