0
votes

When the page load (OnInit) my componentB is directly displayed and i want that the componentB update everytime i click on the submit button.

I have a component A, in this component i have a form and another component componentA. My ts looks like this:

export class componentA implements OnInit {
  testForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.testForm= this.formBuilder.group({
      name: [''],
      username: [''],
    });
  }

  submit(): void {
    console.log('ok');
    console.log(this.partnerForm.get('name').value);
    console.log(this.partnerForm.get('username').value);
    // here i want to refresh my componentB in .html
  }
}

And my html file:

<div>
 <form name="testForm" [formGroup]="testForm" (ngSubmit)="submit()">
  <div>
      <label for="name" position="floating" required>name</label>
      <input ngDefaultControl formControlName="name" name="name" id="name" value="name"></input>
  
      <label for="username" position="floating" required>username</label>
      <input ngDefaultControl formControlName="username" name="username" id="username" value="username></input>
    <button>Submit</button>
  </div>
  </form>
  <componentB [formDaten]="testForm"></componentB>
<div>

My component B looks like this: .ts:

export class componentB implements OnInit {
  @Input() datenForm;

  constructor() { }

  ngOnInit(): void {
    console.log(datenForm.get("name").value);
}

When the page load (OnInit) my componentB is directly displayed and i want that the componentB update everytime i click on the submit button.

Why is the componentB not refreshing ? i also try to make my componentB directly in the form but it didnt work. I also tried to call ngOnInit to refresh the all component but then i will lose my value.

I also think to do it with a subscribe but it is not working with input value

How can i do it ?

1
You need to use EventEmiters fireship.io/lessons/… - Abedin.Zhuniqi
My value change in my parent not in my child ... - Kan
change console from ngOnInit to ngonchanges in componentB, because ngOnInit is invoked only once - Tony

1 Answers

1
votes

implment ngOnChanges event in child component – This event executes every time when a value of an input control within the component has been changed. It always receives a change data , containing the current and previous value of the bound property wrapped in a SimpleChange.

export class componentB implements OnInit, OnChanges {
 @Input() datenForm;

constructor() { }

ngOnInit(): void {
  console.log(datenForm.get("name").value);

ngOnChanges(changes: SimpleChanges) {
 for (let key in changes) {
    console.log(`${key} changed.
    Current: ${changes[key].currentValue}.
    Previous: ${changes[key].previousValue}`);
   }
 }
}