0

My parent Component

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

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
})
export class FormComponent implements OnInit {

  constructor() { }

  from = 'foo'
}
<div class="form">

  <app-text-field [value]="from" [label]="'Label'"></app-text-field>
        
</div>

And another

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

@Component({
  selector: 'app-text-field',
  templateUrl: './text-field.component.html'
})
export class TextFieldComponent implements OnInit {

  constructor() { }
  
  @Input() value: string;
  @Input() label: string = '';

  ngOnInit() {
  }

}
<div class="input">
  <span class="input__name">{{label}}</span>
  <input class="input__input"
    type="text"
    [(ngModel)]="value" />
</div>

And when I type something in textfield it doesn't update my from value. Can ngModel work with @Input string property or it can only correctly work with Objects like this tutorial https://angular.io/tutorial/toh-pt3?

I made some interactive example based on this tutorial https://stackblitz.com/edit/angular-wd69qf as you can see, updating only child component but not parent.

  • I think you should see this [https://stackoverflow.com/questions/35149535/how-can-i-implement-ngmodel-on-custom-elements-own-combobox](https://stackoverflow.com/questions/35149535/how-can-i-implement-ngmodel-on-custom-elements-own-combobox) – Ali Shahbaz Sep 24 '18 at 12:42
  • You can use `@Output() output;` for this and do `this.output.emit(this.value)` where ever you want. – Swoox Sep 24 '18 at 12:43
  • @Swoox he is asking for two-way data binding and this would achieve by only [ControlValueAccessor](https://angular.io/api/forms/ControlValueAccessor) – Ali Shahbaz Sep 24 '18 at 12:46
  • @AliShahbaz Swoox solution suits me in this situation, but yours is more difficult for a person who switches to NG from another framework, although I think that your decision is much smarter and more correct, it will be something to study and think to refactor. Thank you Swoox and AliShahbaz – Roman Nguyen Sep 24 '18 at 13:03

0 Answers0