首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用指令更改@Input属性

使用指令更改@Input属性
EN

Stack Overflow用户
提问于 2021-04-02 05:22:27
回答 1查看 34关注 0票数 0

我有以下组件:

代码语言:javascript
复制
@Component({
  selector: 'box',
  [...]
})
export class BoxComponent {
  @Input() collapsable: boolean = false;
  [...]
}

我可以在<box [collapsable]="true"></box>中使用它,它工作得很好。但我想使用一个指令将属性collapsable更改为<box box-collapsable></box>中的true。

我尝试了以下指令,但它不起作用:

代码语言:javascript
复制
@Directive({
  selector: '[box-collapsable]',
})
export class BoxCollapsableDirective {
  constructor(private el: ElementRef) {}

  ngAfterViewInit(): void {
    this.el.nativeElement.attributes.collapsable = true;
  }
}

我没有得到任何错误,但是BoxComponent中的collapsable保持为false。有没有办法使用指令来改变输入属性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-03 11:03:20

您可以注入BoxComponent实例,而不是将ElementRef注入指令:

代码语言:javascript
复制
@Directive({
  selector: '[box-collapsible]'
})
export class BoxCollapsibleDirective {
  constructor(private box: BoxComponent) {} // <--- inject BoxComponent instance

  ngAfterViewInit() {
    this.box.collapsible = true;
  }
}

这将使您能够直接访问组件的公开属性,包括其输入属性。

演示此方法的Here's a StackBlitz。(一秒钟后,该指令将collapsible从true更改为false。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66911714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档