简体   繁体   中英

Can I use expression in square bracket to access property of class by "this" keyword?

export class AppComponent implements OnInit {
  userSubmitted = false;
  accountSubmitted = false;

  userForm!: FormGroup;

  ngOnInit(): void {}

  onSubmit(type: string): void {
    this[type + 'Submitted'] = true;
    if(this[type + 'Form'].invalid)
      return;
    console.log(this[type + 'Form'].value);
  }

I want to avoid having to write onSubmitUser() and onSubmitAccount() function

Yes, why not! this is an object just like any other object defined inside curly braces {} so there is no reason you cannot do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM