首页 > 解决方案 > 当 Angular 中的输入发生变化时更新组件

问题描述

     <div class=" card-body">
        <div class="row">
          <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active"
            *ngFor="let subject of subjects">
            <div class=" font-icon-detail">
              <div (click)="setSubject(subject.title)" >
                <i class="deep-icons  {{ subject.icon }}"></i>
                <p>{{ subject.title }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
     <subject-component [setSubjectService]="selectedSubject"></subject-component> 

上面的代码来自我的 selector.component.html。

export class SubjectComponent implements OnInit {


@Input() public set setSubjectService(_subjectService: ISubjectService) {
    this.subjectService = _subjectService;
  }

  public subjectService: ISubjectService;

  constructor() {}

  public ngOnInit(): void {

  }
}

上面的代码来自我的 subject.component.ts

现在,主题组件在应用程序启动时被渲染一次,但每当“selectedSubject”更改时,它不会更新或重新渲染。我怎样才能做到这一点?

(使用 Angular 8)

标签: htmlangulartypescript

解决方案


我认为您想使用两种方式绑定。如果是这样; 使用 eventemitter 创建一个输出,例如;

@Input() myVariable: number;
@Output() myVariableChange = new EventEmitter(); //define it nameofyourvariable+Change

constructor() { }

ngOnInit() {}

changeMyVar(v: number) {
   this.myVariable=v;
   this.myVariableChange.emit(myVariable);
}

并使用带括号的两种方式绑定。我的意思是如下:

<subject-component [(setSubjectService)]="selectedSubject"></subject-component>

推荐阅读