我在Angular中有一个应用程序,其中有一个复选框,需要它进行更改才能进行身份验证。这里的想法如下:
我尝试将preventDefault
和click
事件都使用。它可以阻止更改,但不允许我动态设置。我也尝试了以下方法:
HTML:
change
Typescript:
<div class="pull-right">
<input id="authenticate" type="checkbox" [(ngModel)]="IsAuthenticated" (ngModelChange)="CheckForAuthentication($event)"/>
<label class="label" for="authenticate">
<span>Authenticate</span>
</label>
</div>
使用getter / setter轻松完成
HTML
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.scss']
})
export class AuthenticationComponent implements OnInit {
IsAuthenticated: boolean = false;
constructor(protected service: AuthenticationService) {}
ngOnInit() {}
async CheckForAuthentication(value: boolean) {
// If we're unchecking don't do anything
if (!value) {
return;
}
// Remain false until authentication is complete
this.IsAuthenticated = false;
// Wait for authentication
const authenticated = await this.service.Authenticate();
// If authentication is true, change the checkbox
this.IsAuthenticated = authenticated;
}
}
打字稿
<div class="pull-right">
<input id="authenticate" type="checkbox" [(ngModel)]="IsAuthenticated" />
<label class="label" for="authenticate">
<span>Authenticate</span>
</label>