代码之家  ›  专栏  ›  技术社区  ›  Joseph

无法在Angular 4中绑定属性

  •  0
  • Joseph  · 技术社区  · 7 年前

    为什么在同一组件上绑定属性时会出现问题?我已经添加了Input(),但仍然不起作用。绑定时,即使输入()在同一个组件上,我也需要放置它吗?

    //output.component.ts
    import { Component, OnInit} from '@angular/core';
    import { DataService } from '../data.service';
    @Component({
      selector: 'app-output',
      templateUrl: './output.component.html',
      styleUrls: ['./output.component.css']
    })
    export class OutputComponent implements OnInit {
    data: {name: string};
    datas = [];
    
    constructor(private dataService: DataService) { }
    
    ngOnInit(){
       this.datas = this.dataService.datas;
    }
    }
    
    
    
    //output.component.html
    <p *ngFor="let data of datas"></p>
    <p>{{data.name}}</p>
    
    
    //data.service.ts
    export class DataService {
      datas= [];
    
      addData(name: string){
         return this.datas.push({name: name});
      } 
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   micronyks    7 年前

    对于相同组件 @input API 不需要。当您希望将数据从父组件传递到子组件时,将使用它。

    //output.component.html
    <p *ngFor="let data of dataService.datas" >  // removed [data]="data" and added dataService.datas
       <p>{{data?.name}}</p>
    </p>                                         //changed the position of </p>
    
    
    export class OutputComponent implements OnInit {
       constructor(private dataService: DataService) {}
    }
    

    export class DataService {
       datas= [];
    
       addData(name: string){
          return this.datas.push({name: name});   //return keyword was missing
       } 
    }
    

    仅供参考

    演示: https://plnkr.co/edit/XlJM2LHFwlAYpQe2ancM?p=preview

    推荐文章