@input双向绑定不起作用

时间:2017-10-23 10:48:05

标签: javascript angular typescript

我想访问我的子组件中的文本区域中的文本,将其放在父组件上并保持更新。

我被告知角度为4的@input应该执行双向绑定。但我不能这样做,我也不明白为什么。

我找到了解决此问题的方法。它包含一个@Output,用于将信息发送到父组件。但如果输入已经这样做(在某种程度上我不知道),我想避免它。

例如,这是我的父组件

import { Component } from '@angular/core';

@Component({
    selector: 'app-settings',
    templateUrl: './settings.component.html',
})
export class SettingsComponent {

    private studyDesignText =  'Text';

    constructor() {
    }

    public handleStudyDesignUpdated(designText: any) {
        this.studyDesignText = designText;
    }

}

它的HTML

<div class="section section-trials-settings-parent light rounded">
  <div class="section section-trials-settings-child">
    <div class="pure-g">
      <div class="pure-u-1-1">
        <app-settings-study-design
          [studyDesignText]="studyDesignText">
        </app-settings-study-design>
      </div>
    </div>
  </div>
</div>

我的孩子组成部分:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-settings-study-design',
  templateUrl: './settings-study-design.component.html',
})
export class SettingsStudyDesignComponent implements OnInit {

  @Input() studyDesignText: string;

  constructor() {
  }

  ngOnInit() {
    super.onInit();
    loadControls();
  }

  loadControls(): void {
    this.startAllTextAreas();
  }

  private startAllTextAreas() {
    this.startTextArea('study-design-textarea');
  }

  private startTextArea(htmlId: string) {
    // code to configure my text area; it's right...

}

如果我更改文本区域中的值并使用@Output发送信号,以便可以通知我的父组件并且控制台记录该值,则打印值是初始值。我的朋友做了同样的事情并且有效。

我错过了什么?

1 个答案:

答案 0 :(得分:4)

var didEnterBackgroundNotificationName = NSNotification.Name.UIApplicationDidEnterBackground.rawValue var willEnterForgroundNotificationName = NSNotification.Name.UIApplicationWillEnterForeground.rawValue let address1 : Int = address(of: &didEnterBackgroundNotificationName) let address2 : Int = address(of: &willEnterForgroundNotificationName) if address1 != 0 && address2 != 0 { // code here } 始终是从@Input()绑定的一种方式。在这种情况下,只有当您将parent->child作为输入属性时才会发生双向绑定。这是因为,对象的引用保持不变。当其中一个对象更新时,另一个也会更新。对于objectstring,情况并非如此。它总是单向绑定。

相关问题