Databinding from within a template in angular

可紊 提交于 2019-12-13 03:52:50

问题


In a component how to databind two-way for the following example: I want the button's text to toggle automatically when I am setting or unsetting dataitem.isSelected in the respective methods

Here is the code of 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
     }
}

回答1:


Just remove this part let-dataitem="item" from here <ng-template 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>

Embedded views that are created from the ng-template have access to the properties on the parent component, so it should be updated whenever Angular runs change detection. Here is the plunker and the code that emulates your case:

@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);
  }
}


来源:https://stackoverflow.com/questions/45198044/databinding-from-within-a-template-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!