Angular 이벤트 처리

    Angular 이벤트는 사용자 상호작용에 대한 응답으로 방출됩니다. Angular 이벤트가 방출되면 해당 이벤트 처리 로직이 실행됩니다. WPF는 라우트된 이벤트, CLR 이벤트 및 명령을 제공합니다. Angular 에는 DOM 이벤트가 있습니다.

    다음은 WPF에서 버튼의 클릭 이벤트에 응답하는 방법의 간단한 예입니다.

    <Button Click="Button_Click">Click Me</Button>
    xml
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine("Hello World");
    }
    csharp

    Angular 에서는 같은 내용이 다음과 같습니다.

    <button (click)="onClicked()">Click Me</button>
    html
    onClicked() {
        console.log('Hello World');
    }
    typescript

    WPF에서는 발신자 및 이벤트 인수와 같은 이벤트에 대한 정보를 얻는 데 익숙합니다. Angular 에서는 $event 변수를 사용할 수 있습니다. 이 변수는 호출된 이벤트에 대한 정보를 제공합니다.

    <button (click)="onClicked($event)">Click Me</button>
    html
    onClicked(event) {
        console.log(event.target);
    }
    typescript

    때로는 이벤트 객체를 전달하는 것이 별로 유용하지 않을 수도 있습니다. 대신 페이지의 input 값을 전달할 수 있습니다.

    <input #messageInput>
    <button (click)="onClicked(messageInput.value)">Click Me</button>
    html
    onClicked(message) {
        console.log(message);
    }
    typescript

    Enter를 누르면 입력 값을 인쇄하고 싶다고 가정해 보겠습니다. Angular에서 다음과 같이 할 수 있습니다.

    <input #messageInput (keyup)="onInputKeyup($event, messageInput.value)">
    html
    onInputKeyup(event, message) {
        if (event.keyCode === 13) {
            console.log(message);
        }
    }
    typescript

    놀랍게도 Angular 에서는 더 쉬운 방법이 있습니다. keyup.enter 가상 이벤트에 바인딩할 수 있습니다. 이 접근 방식을 사용하면 사용자가 Enter를 누를 때만 이벤트 핸들러가 호출됩니다.

    <input #messageInput (keyup.enter)="onInputKeyup(messageInput.value)">
    html
    onInputKeyup(message) {
        console.log(message);
    }
    typescript

    Responding to Events of a Component

    WPF에서 사용자 정의 컨트롤을 만들 때 다음과 같은 일부 기본 이벤트를 확장하거나 수정해야 하는 경우가 많습니다.

    public class MyControl : Control
    {
        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);
            // Place your custom logic here
        }
    }
    csharp

    Angular 에서는 HostListener 데코레이터를 사용하여 비슷한 결과를 얻을 수 있습니다.

    @Component({
        selector: 'app-my-component',
        templateUrl: './my.component.html',
        styleUrls: ['./my.component.css']
    })
    export class MyComponent {
        @HostListener('mousedown', ['$event'])
        onMouseDown(event) {
            // place your custom logic here
        }
    }
    typescript

    Create Your Own Events

    때로는 자신만의 이벤트를 정의해야 할 때도 있습니다. WPF에서는 CLR 또는 라우트된 이벤트를 정의할 수 있습니다. WPF의 CLR 이벤트에 대한 간단한 예를 살펴보겠습니다.

    public event EventHandler<TaskEventArgs> TaskCompleted;
    
    ...
    this.TaskCompleted(this, new TaskEventArgs());
    csharp

    Angular에서 사용자 정의 이벤트를 정의하려면 Output 데코레이터로 표시된 EventEmitter 속성을 정의해야 합니다.

    @Output()
    taskCompleted = new EventEmitter<TaskEventArgs>();
    
    ...
    this.taskCompleted.emit(new TaskEventArgs());
    typescript

    Additional Resources

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.