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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
  private _username: string = '';

  @Output()
  usernameChange = new EventEmitter<string>();

  @Input()
  public get username(): string {
    return this._username;
  }

  public set username(value: string) {
    this._username = value;
    this.usernameChange.emit(value)
  }

  handleInput(e: Event) {
    this.username = (e.target as HTMLInputElement).value;
  }

}
<input type='text' [value]="username" (input)="handleInput($event)" placeholder="用户名"/>{{username}}

使用:

<app-test [(username)]="username"></app-test>