使用@input将数据传输到组件

typescript
阅读 66 收藏 0 点赞 0 评论 0

parent.component.ts
import { Component ,Input} from '@angular2/core';
import { ChildComponent } from './child.component';
import { Character } from './character';

@Component({
  selector: 'story-app',
  template: `
  <div style = "border:2px solid orange; padding:5px;">
    <h1>Parent Component</h1>
    <input [(ngModel)] = "characters[0].name"/>
    <button (click)="select(characters[0])">Input</button>
    <br/><br/>
    <story-characters  [character]="selectedCharacter"></story-characters>
  </div>
  `,
  directives:[ChildComponent]
})

export class ParentComponent{
  characters = [
    {
      "id":11,
      "name":"Name"
    }];
    
    selectedCharacter: Character;
    
    select(selectedCharacter : character){
      this.selectedCharacter = selectedCharacter;
    }
}
index.html
<story-app>
    loading...
</story-app>
child.component.ts
import { Component, Input} from '@angular2/core';
import { Character} from './character';
@Component({
  selector: 'story-characters',
  template:`
  <div style="border:2px solid orange; padding:5px">
    <h1>Child Component: <span *ngIf="character">{{character.name}}</span></h1>
  </div>
  `
})
export class ChildComponent {
   @Input() character: Character;
}
character.ts
export class Character{
  constructor(public id: number, public name: string){ }
}
评论列表


问题


面经


文章

微信
公众号

扫码关注公众号