html 将元素从父组件绑定到子组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 将元素从父组件绑定到子组件相关的知识,希望对你有一定的参考价值。

<div class="panel panel-default">
  <div class="panel-heading">{{ element.type }}</div>
  <div class="panel-body">{{ element.name }} - {{ element.content }}</div>
</div>
import { Component, OnInit, Input } from '@angular/core'; // allow Input

@Component({
  selector: 'app-server-element',
  templateUrl: './server-element.component.html',
  styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {
  @Input() element: {type: string, name: string, content: string}; // Bind 'element' to Parent Component with @Input
  // NOTE: optional adding Alias 
  // @Input('srvElement') element: {...} 
  // [app.component.html] must now use [srvElement]="serverElement"
  
  constructor() { }

  ngOnInit() {
  }

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements = [{type: 'server', name: 'Testserver', content: 'Just a test'}];

}
<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <app-server-element 
        *ngFor="let serverElement of serverElements" 
        [element]="serverElement"></app-server-element> <!-- Child Component uses Alias 'element' (ex. element.name) so we will make 'element' be 'serverElement' -->
    </div>
  </div>
</div>

以上是关于html 将元素从父组件绑定到子组件的主要内容,如果未能解决你的问题,请参考以下文章

ReactJS setState 更改不会从父组件传播到子组件[重复]

如何将道具从父组件添加到子组件的子组件

如何将道具从父组件渲染到子组件?

使用@Input 将异步值从父组件传递到子组件

Angular中从父组件到子组件的数据共享

从父组件到子组件的到达点击处理程序不起作用