简体   繁体   中英

Property 'alertService' and 'options' does not exist on type 'AppComponent'

I'm implementing alert services in my applications however I get the error Property 'alertService' does not exist on type 'AppComponent' and Property 'options' does not exist on type 'AppComponent'

app.component.html:

<div class="form-group">
   <button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold" 
   (click)="alertService.success('Success!!', options)">Submit</button>
</div>

app.component.ts:

export class AppComponent {
  public frmSignup: FormGroup;
  public message = "Congrats you have successfully created your account";

  constructor(private fb: FormBuilder) {
    this.frmSignup = this.createSignupForm();
  }

  createSignupForm(): FormGroup {
    return this.fb.group(
      {
       ........
      }
    );
  }

  submit() {
    // do signup or something
    console.log(this.frmSignup.value);
    alert(this.message);
  }

You need to explicity inject the alertService in the constructor of AppComponent

constructor(private fb: FormBuilder, alertService: AlertService) {
    this.frmSignup = this.createSignupForm();
    this.alertService = alertService;
}

The options need to be set as well in the Component as a public property.


However:

The better option would be to create a class method, that you can call on click event:

<div class="form-group">
   <button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold" 
   (click)="handleClick()">Submit</button>
</div>
export class AppComponent {
  public frmSignup: FormGroup;
  public message = "Congrats you have successfully created your account";
  options = {};

  constructor(private fb: FormBuilder, private alertService: AlertService) {
    this.frmSignup = this.createSignupForm();
  }

  createSignupForm(): FormGroup {
    return this.fb.group(
      {
       ........
      }
    );
  }

  submit() {
    // do signup or something
    console.log(this.frmSignup.value);
    alert(this.message);
  }
  
  handleClick() {
    this.alertService.success('Success!!', options);
  }
}

Note: I don't understand, why the submit button doesn't call the submit method...

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