将js转换成打字稿成角度8

时间:2021-04-01 03:16:55

标签: javascript angular typescript angular8

下面的代码在 javascript 中运行良好。但是当我在 Angular 8 中尝试同样的方法时,我遇到了很多错误

const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');

signUpButton.addEventListener('click', () => {
    container.classList.add('right-panel-active');
});

signInButton.addEventListener('click', () => {
    container.classList.remove('right-panel-active');
});
} 

错误 signUpButton.addEventListener('click', () => { ~ 错误 TS1003:需要标识符。

    69 signUpButton.addEventListener('click', () => {
                                         ~~~~~~~
    Parameter declaration expected.

    69 signUpButton.addEventListener('click', () => {
                                                ~
    Parameter declaration expected.

    69 signUpButton.addEventListener('click', () => {
                                                  ~
    error TS1005: ';' expected.

    71 });
            ~
    error TS1128: Declaration or statement expected.

请告诉我如何将其转换为 Typescript

2 个答案:

答案 0 :(得分:1)

在 Angular 中,最好不要在 HTML 代码中使用 eventListeners 而是使用事件绑定。

您的 HTML 将类似于:

<input type="button" name="" id="signUp" (click)="signUp()">
<input type="button" name="" id="signIn" (click)="signIn()">

并在 TS 文件中:

signUp() {
    const container = document.getElementById('container');
    container.classList.add('right-panel-active');
}

signIn() {
    const container = document.getElementById('container');
    container.classList.remove('right-panel-active');
}

阅读更多内容 --> https://angular.io/guide/event-binding

答案 1 :(得分:-1)

.ts 文件中按原样试试这个,你的代码中有一个额外的花括号,

const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');

signUpButton.addEventListener('click', () => {
    container.classList.add('right-panel-active');
});

signInButton.addEventListener('click', () => {
    container.classList.remove('right-panel-active');
});