Angular feature: Utilizing the @Output decorator for subscribing to EventEmitter

I have created a custom directive featuring an @Output EventEmitter:

@Directive({
    selector: '[ifValid]'
})
export class SubmitValidationDirective {

    @Output('ifValid') valid = new EventEmitter<void>();

    constructor(
        private formRef: NgForm
    ) {}

    @HostListener('click')
    handleClick() {
        this.emitIfValid();
    }

    private emitIfValid() {
        if (this.formRef.valid) {
           this.valid.emit();
        }
    }

}

Now, I am using it in this manner:

<button (ifValid)="save()">

In my component, the save() function looks like:

private save() {
    this.service.push(this.user, this.toCreate)
       .pipe(
           take(1)
       )
       .subscribe();
}

I find manual subscription to be bothersome.

I would like to automatically add the operator

switchMap(() => this.service.push(...))
when ifValid is triggered.

Is it possible to subscribe to ifValid outside of HTML, directly within my component?

I hope this explanation is clear.

Answer №1

If you want to implement form validation in your component, you can utilize

@ViewChild(SubmitValidationDirective) directive;
and then proceed with the following code:

this.directive.valid.subscribe(() => {this.service.add(this.user, this.toCreate)
       .pipe(
           take(1)
       )
       .subscribe();
});

Remember to call unsubscribe() in a lifecycle hook like ngOnDestroy.

Answer №2

Sure, you have the capability to achieve this task by creating a dedicated service and defining the @Output property within that service.

The SharedService:

@Output('ifValid') valid = new EventEmitter<void>();

The componentOne:

ngOnInit() {
this.sharedService.valid.subscribe(resp => {
     this.save()
});
}

private save() {
    this.service.push(this.user, this.toCreate)
       .pipe(
           take(1)
       )
       .subscribe();
}

The Directive or Component:

import { SharedService } from 'Sharedservice';

@Directive({
    selector: '[ifValid]'
})
export class SubmitValidationDirective {
    constructor(private sharedService: SharedService) { }
    @Output('ifValid') valid = new EventEmitter<void>();

    constructor(
        private formRef: NgForm
    ) {}

    @HostListener('click')
    handleClick() {
        this.emitIfValid();
    }

    private emitIfValid() {
        if (this.formRef.valid) {
          this.sharedService.valid.emit(null);
        }
    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Developing a hybrid application with .Net Core and Angular 2 is an achievable task

https://i.sstatic.net/hWlHp.png Currently, I am working on developing an application that involves utilizing .net core and angular2 technologies. Is it possible to integrate an angular component within Razor view Pages seamlessly? ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Steps for styling the header of an Antd Collapse Panel

I'm attempting to modify the text color in the header of an ant panel. Below is the entire ant collapse component code: <Collapse accordion defaultActiveKey={defaultOpenPanel}> <StyledCollapsePanel key="tasksAssignedToMe" header={ ...

An issue with the Pipe searchByType is resulting in an error stating that the property 'type' is not found on the type 'unknown'

I keep encountering a range of errors like roperty does not exist on type 'unknown' after running the command ionic build --prod --release src/app/pages/top-media/top-media.page.ts:18:16 18 templateUrl: './top-media.page.html', ...

After the "markerClick" event triggers in Angular2 SebmGoogleMapMarker, the view fails to update

I am dealing with an array structured like this: locations: marker[] = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)', iconUrl: 'img/marker.png'}, {id: '2&apos ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Improving DynamoDb Query Results with Type Hinting

In the following Typescript code, how can I specify which fields should be present in my Query Items Result? const request: DynamoDB.DocumentClient.QueryInput = { TableName: UnsubscriptionTokensRepository.TABLE_NAME, IndexName: 'TokenIndex&ap ...

Guide on exporting member formModule in angular

After compiling my code in cmd, an error message is displayed: ERROR in src/app/app.module.ts(3,10): error TS2305: Module '"C:/Users/Amir_JKO/my-first-app/node_modules/@angular/forms/forms"' does not have an exported member 'formModul ...

I am trying to populate my React hook form with existing data so that I can easily make updates to my task

I am struggling with prefilling my react hook form. Currently, I am seeing [object Object],[object Object],[object Object],[object Object],[object Object] in my input field. Can anyone help me understand how to extract the content of the object to automat ...

Using Typescript in conjunction with nodemon and VS Code for seamless integration of declaration merging

After adding a middleware to my express app app.use(function(req: express.Request, res: express.Response, next: express.NextFunction) { req.rawBody = 'hello2'; next(); }); I also included custom.d.ts declare namespace Express { expor ...

Step-by-step guide on setting fa fa-check as the background image for the selected field in Angular 4 with ng-select

I am implementing an ng-select field and would like to display a check mark for the selected option in the dropdown list using fontawesome check. However, I am unsure of how to achieve this. Can anyone provide guidance? HTML: <ng-select class="box" p ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

Is it possible for a Firestore query using .where() to conduct a search with no results?

Currently, I am in the process of creating a platform where users can upload past exams. Each document contains various fields such as teacher, year, and class, all stored in cloud Firestore. To filter the data by teacher, I am using the .where("Teacher" ...

Adding to object properties in Typescript

My goal is to dynamically generate an object: newData = { column1: "", column2: "", column3: "", ... columnN: "" } The column names are derived from another array of objects called tableColumns, which acts as a global variable: table ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...