根据属性值使用类

时间:2019-05-15 10:56:04

标签: angular angular6

[ngClass]在尝试根据class的属性选择Css类时不起作用。

[ngClass]="{'alert alert-danger': employeeForm.get('fullname').errors && (employeeForm.get('fullname').touched || employeeForm.get('fullname').dirty) }"

以上代码在*ngIf中有效,但在[ngClass]中无效。

我正在关注youtube tutorial

export class CreateEmployeeComponent implements OnInit {
  employeeForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.employeeForm = this.fb.group({
      fullname: ['', Validators.required ],
      email: [''],

      skills : this.fb.group({
        skillName: [''],
        experience: [''],
        proficiency: ['beginner']
      })
    });
  }

  onLoadDataClick(): void {
    this.employeeForm.setValue({
      fullname: 'Jamshaid Tariq',
      email: 'jamshaid055@yahoo.com',
      skills: {
        skillName: 'C#',
        experience: 1,
        proficiency: 'beginner'
      }
    });
  }

  onSubmit(): void {
    console.log(this.employeeForm.value);
  }

}

2 个答案:

答案 0 :(得分:1)

通过添加!!来确保它是布尔值:

[ngClass]="{'alert alert-danger': !!(employeeForm.get('fullname').errors && (employeeForm.get('fullname').touched || employeeForm.get('fullname').dirty)) }"

我接受了您的代码,此方法有效。我只加了一个!去测试 https://stackblitz.com/edit/angular-fquu8t

答案 1 :(得分:0)

我认为应该是[class]

[class]="enalbleClass?'class-custom':''"

因此,您必须在组件中编写逻辑来处理此问题。像

this.enalbleClass = employeeForm.get('fullname').errors && (employeeForm.get('fullname').touched || employeeForm.get('fullname').dirty)