【问题标题】:Databinding from within a template in angular角度模板内的数据绑定
【发布时间】:2017-12-25 04:00:32
【问题描述】:

在一个组件中如何进行双向数据绑定,例如: 当我在各自的方法中设置或取消设置 dataitem.isSelected 时,我希望按钮的文本自动切换

这里是channelstab.component.ts的代码

@Component({
  selector: 'channels-tab',
  template: `
    <ListView [items]="channels$ | async" class="list-group">
        <ng-template let-dataitem="item">
           <Button [text]="dataitem.isSelected?'UnFollow':'follow'" (tap)="dataitem.isSelected?unfollow(dataitem):follow(dataitem)"></Button>
        </ng-template>
    </ListView>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChannelsTabComponent implements OnInit {
     public channels$: Observable<any>;
     ngOnInit() {
       this.channels$ = <any>this.someService.get('channels');
     }
     unfollow(dataitem) {
        dataitem.isSelected = false;//not working
     }
     follow(dataitem) {
        dataitem.isSelected = true;//not working
     }
}

【问题讨论】:

  • 这些函数是在哪里定义的?
  • 在同一个组件中,更新了代码以包含其他部分。
  • 尝试删除这个let-dataitem="item",它应该从组件的上下文中读取dataitem
  • 将 ChangeDetectionStrategy 从 OnPush 更改为 Default 似乎已经解决了问题

标签: angular data-binding angular2-nativescript


【解决方案1】:

只需从这里&lt;ng-template let-dataitem="item"&gt; 删除这部分let-dataitem="item"

<ListView [items]="channels$ | async" class="list-group">
    <ng-template>
       <Button [text]="dataitem.isSelected?'UnFollow':'follow'" (tap)="dataitem.isSelected?unfollow(dataitem):follow(dataitem)"></Button>
    </ng-template>
</ListView>

ng-template 创建的嵌入式视图可以访问父组件上的属性,因此每当 Angular 运行更改检测时都应该更新它。 Here is the plunker 和模拟您的案例的代码:

@Component({
  selector: 'test',
  template: `{{name}}`
})
export class TestComponent {
  @Input() name;
}

@Component({
  selector: 'my-app',
  template: `
    <ng-template #t>
      <test [name]="name"></test>
    </ng-template>
    <ng-container #vc></ng-container>
  `,
})
export class App {
  @ViewChild('vc', {read: ViewContainerRef}) vc;
  @ViewChild('t', {read: TemplateRef}) t;

  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`;

    setTimeout(()=>{
      this.name='changed';
    }, 3000);
  }

  ngOnInit() {
    this.vc.createEmbeddedView(this.t);
  }
}

【讨论】:

  • 我还是看不懂,怎么能从组件中读取dataitem。在组件的构造函数中,我只有 channel$ 这是一个 Observable。你能指出我在模板示例中对 Observable 进行循环吗?
  • 或者更好的是创建一个简单的 plunker
  • plunker 不工作,确保它工作,以便我看看
  • 这是一个移动应用程序。plunker 不起作用。尝试用 ul 替换 listview,但不确定 plunker 是如何计算的。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2014-06-30
  • 2017-09-25
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
相关资源
最近更新 更多