Angular5 - Change parent's property from child component's input's [(ngModel)] binding

橙三吉。 提交于 2019-12-24 04:11:25

问题


I have already looked at this similar question without success. The plunker mentioned in the question seems to be broken.

I am trying to update parent component's property from child component's [(ngModel)] binding.

This is the child components HTML:

<div class="elastic-textarea">
    <ion-input rows="1"  [value]="inputValue" [(ngModel)]="inputValue" (ngModelChange)="change($event)" ></ion-input>
    </div>

This is the child components TS:

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

@Component({
  selector: 'app-childinput',
  templateUrl: './childinput.component.html',
  styleUrls: ['./childinput.component.css']
})
export class ChildinputComponent  {
@Input() inputValue: string;
  @Output() emitInputValue = new EventEmitter();
  constructor() { }

change(newValue) {
    console.log('newvalue', newValue)
    this.inputValue = newValue;
    this.emitInputValue.emit(newValue);
  }
}

This is how I'm using the child component in the parent component:

<app-childinput [(inputValue)]="thevalue" ></app-childinput>
<p>The changed value should be reflected here: {{thevalue}}</p>

Here is a STACKBLITZ demonstrating the issue. The parent component is the page callled "home", and the child component is the component called "childinput."

Am I doing something wrong or is this simply not possible anymore in Angular?


回答1:


Just change emitInputValue to inputValueChange.

Fixed Stackblitz




回答2:


childinput.component.html

<div class="elastic-textarea">
    <ion-input rows="1"  [value]="inputValue" [ngModel]="inputValue" (ngModelChange)="change($event)" ></ion-input>
</div>

home.html and home.ts change

<app-childinput [(inputValue)]="thevalue" ></app-childinput>

to

<app-childinput [inputValue]="thevalue" (emitInputValue)="update($event)" ></app-childinput>


update(event) {
    this.thevalue = event;
  }

You declared Output EventEmitter emitInputValue, you didn't emit it properly. [(ngModel)] is two way binding which you mixed it with your Input decorator inputValue



来源:https://stackoverflow.com/questions/52081579/angular5-change-parents-property-from-child-components-inputs-ngmodel-b

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