AOT - Angular 6 - Directive SomeComponent, Expected 0 arguments, but got 1. for self made Component
Asked Answered
R

4

54

I am facing issue when i want to compile my current project in AOT with following package version :

my webpack and tsconfig.json configuration can be find here

I have facing some issue related to private / protected scope used on template and some extract parameter gived to some functions who doesn't really need it (Exemple $event who are not used on EventBinding).

Now i have this following list where i can't find where is my issue :

/path/to/app/header/main-header/main-header.component.html(85,7): : Directive TableOfContentComponent, Expected 0 arguments, but got 1. (1,1): : Directive TableOfContentComponent, Expected 0 arguments, but got 1.

my main-header.component.html file contain : // main-header.component.html

// main-header.component.ts
@ViewChildren('headerItems') public headerItems: QueryList<HeaderItemAbstract>;
mainMenuStates = {
    hamburger: false,
    bookmarks: false,
    search: false,
    toc: false,
    medias: false,
    article: false,
    language: false    
};

And my TableOfContentComponent does not contain any @Input property.

@Component({
    selector: 'ps-table-of-content-template',
    templateUrl: './table-of-content.component.html',
    animations: [slideUpAndDownAnimation]
})
export class TableOfContentComponent extends HeaderItemAbstract implements OnInit {

    toc: TableOfContentModel[];

    devices: DevicesModel;

    tocContentHeight: number;
    tocContentMargin: number;
    menuHeight: string;


    constructor(private tableOfContentService: TableOfContentService,
                private deviceService: DeviceService,
                private elemRef: ElementRef) {
        super();
        this.toc = this.tableOfContentService.tableOfContent;
    }
}

/path/to/app/header/main-header/hamburger-menu/hamburger-menu.component.html(125,5): : Directive SliderComponent, Expected 0 arguments, but got 1. (1,1): : Directive SliderComponent, Expected 0 arguments, but got 1.

my hamburger-menu.component.html is close to above presented code :

<ps-slider-component [template]="slidable" [countItems]="associatedDocuments.length">
    <ng-template #slidable>
        <ul class="clearfix">
            <li class="ps-hmt-associated-item-wrapper pull-left slider-item"
                *ngFor="let document of associatedDocuments">
                <a href="{{ document.link }}" target="_blank" class="btn-nostyle">
                    <div class="ps-hmt-image">
                        <img src="{{ document.images.thumbnail }}" alt="">
                    </div>
                    <p class="ps-hmt-title slider-text"
                        [matTooltip]="isArticleView ? null : document.title"
                        [matTooltipPosition]="'above'"
                        [matTooltipClass]="['ps-mat-tooltip', 'ps-mat-tooltip-doc']"
                    >
                        {{ document.title }}
                    </p>
                </a>
            </li>
        </ul>
    </ng-template>
</ps-slider-component>
// On ts side
associatedDocuments: Array<AssociatedDocumentModel>;
@ViewChild('slidable') slidable: ElementRef;

And my SliderComponent looks like :

export class SliderComponent extends UnsubscribeHelper implements OnInit, OnChanges {

    @Input() template: ElementRef;
    @Input() countItems: number;
    @Input() resetSlide ?: null;
    @Input() fixedHeight?: null;
    @Input() isVariableWidth?: null;
    @Input() isBookmarks?: null;
    @Input() hasSkeleton?: boolean = false;

/path/to/app/header/main-header/medias/dialogs/image-dialog.component.html(34,5): : Directive CarouselComponent, Expected 0 arguments, but got 1. (1,1): : Directive CarouselComponent, Expected 0 arguments, but got 1.

Really close to previous one, i thinks issue is same.

/path/to/app/document/page/page.component.html(7,9): : Directive InfinityPageScrollComponent, Expected 0 arguments, but got 1. (1,1): : Directive InfinityPageScrollComponent, Expected 0 arguments, but got 1.

Here we don't have any input on InfinityPageScrollComponent and tag is call like this <ps-infinity-page-scroll></ps-infinity-page-scroll>

I precise, when i disable AOT on my webpack everything work like charm.

i have try to find solution on AoT Do's and Don'ts without any result.

I have also notice if i disable fullTemplateTypeCheck i am facing around 18 000 errors with some implicit any type and more strange, undefined property for my service declared on the constructor.

--- EDIT 1 : Provide code for Abstract class : UnsubscribeHelper---

export abstract class HeaderItemAbstract extends UnsubscribeHelper implements AfterViewInit {
    public toggleItem: string = 'out';
    public ANIMATION_DURATION = slideUpAndDownAnimationDuration;

    constructor() {
        super();
    }

    // [Some other method]
    /**
     * Self animate after loading on DOM
     */
    ngAfterViewInit()
    {
        // Wait next to to avoid error :
        // ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
        setTimeout(() => {
            this.toggleAnimation();
        },100);
    }
}

Code for abstract class UnsubscribeHelper :

export abstract class UnsubscribeHelper implements OnDestroy {

    subscriptions: Subscription[] = [];

    ngOnDestroy() {
        this.subscriptions.forEach(sub => sub.unsubscribe());
    }

    addSubscription(subscription: Subscription) {
        this.subscriptions.push(subscription);
    }
}
Rosati answered 18/5, 2018 at 7:23 Comment(8)
Could you also provide the code of your superclass HeaderItemAbstract ?Rayon
@trichetriche sure i have added my two Abstract class requiredRosati
Thank you. For readability purposes, I also suggest you to remove the configuration of your project, as the issue is about your classes (which I'm trying to find)Rayon
yes is true, i wil move it to pastbin.Rosati
are tableOfContentService and DeviceService decorated with @Injectable() ?Rayon
Yes both are decorated by @Injectable() and they are part of the same NgModuleRosati
Then I don't see your issue. The error states that you provide an argument to a constructor where it doesn't expect one, but from what you posted, that's not the case ... Could you make a minimal reproducible example on stackblitz with your project ?Rayon
@trichetriche i have finally find my mistake when i have prepared minimal sample. Thanks again for your helpRosati
R
198

Well I have prepared here a minimal, complete, and verifiable example

I have noticed a missing parameter with @HostListner

sample of issue bellow :

@HostListener('window:resize', ['$event'])
onResize(): void {
    
}

simply remove '$event' and it works great.

In conclusion this two options work properly :

// When you need the Event variable, you can use following syntax.
@HostListener('window:resize', ['$event'])
onResize($event: Event): void {
    
}

// When you do not need the Event variable, you can use following syntax.
@HostListener('window:resize')
onResize(): void {
    
}

Thanks to @trichetriche for your help.

Rosati answered 18/5, 2018 at 10:41 Comment(11)
This saves me a lot of time. That is so weird and so inaccurate that the compiler doesn't tell me when the problem actually is. Thanks againFeldspar
Is because annotation are not well integrate on AOT compilation.. big head heck to notice this point :)Rosati
I lost 2 hours before doing the right Google Search to get to this. I really couldn't figure out which argument was not expected!!!! THANKS!! And Merry Xmas!!Mauricio
Still present in Angular 8.2.7. See issue #32828 at Github of Angular. Sometime it works. It's a random error in my experience. In another project it works. (Same deps, same env, same stuff) And the best thing is, that this error has no file path and no member name. Nothing. You have to find it out successively.Krug
How the $event will work then? Removing $event will build but won't work in scenarios where we require window object etc etc.. So, the solution can be you can add event parameter in the calling function, even if you don't need to use it.Amphora
Note: this error of course can also happen if you have the listener defined in the host input of the @Component decorator options: @Component({host: {'click': 'handleClick($event)'}})Rowenarowland
Error just happened again after migrating from Angular v10 to v11Cyclonite
can you update your answer placing how your code is after updating and working properly?Copulate
Sure, have edited, it is better now ?Rosati
@electrovir, how do you solve the issue in this case - @Component({host: {'click': 'handleClick($event)'}}) ?Lazo
@KarthikBhat by having public handleClick($event: MouseEvent) signature for your methodRosati
P
38

I meet some similar error called ERROR in (1,1): : Directive SomeComponent, Expected 0 arguments, but got 1. as described inside this comment https://mcmap.net/q/334540/-aot-angular-6-directive-somecomponent-expected-0-arguments-but-got-1-for-self-made-component, but now it was happened with window:scroll

@HostListener('window:scroll', ['$event']) public onScroll(): void {
  ...
}

It not so obvious, because Directive defined inside the component (@HostListener) is like anonymous directive here in the message, and not so clear where I had to search for it. I solve this message with logic: if we provide $event to function called onScroll - we need to set here argument event like onScroll(event), so there are no arguments inside function handler of HostListener directive, and we receive this error. But it happened in my case in line 1, as described in error message, but @HostListener was declared below all the functions, and by hoisting and optimisations maybe, it appeared in line 1.

Solved code:

@HostListener('window:scroll', ['$event']) public onScroll(event /*provide $event to method here */): void {
  ...
}
Plosion answered 12/9, 2019 at 14:33 Comment(6)
@HostListener is a directive. It's method has no arguments, but implicitly need it. Set (event) argument to the method and solve the issue :)Plosion
Great. It works but I just removed $event from the HostListner. It is workingSafier
Thank you for the answer. This answer is better than the one with most vote as it tells you why this exception is there.Gussy
Bingo! This is the answer which helped me. Thank you.Vickery
I think this should be the answer, and it worked for me as well. whereas the selected one didn't, as I needed the event in my methodHighflier
THIS SHOULD BE THE ACCEPTED ANSWERWellappointed
T
1

I'm adding an additional answer that hopefully will help others searching for this same error message but with a different problem.

In my situation I had difference in signature for a method being overridden in the base class.

export class Foo extends BaseFoo {

   // NOTE: Missing (parameter)
   onBlur() {
      this.touched();
   }
}

export class BaseFoo {
    onBlur(target: any) {
        ...
    }
 }

Then in the same component I was missing the parameter in the template:

<div tabindex="0" (blur)="onBlur()>...</>
Tieck answered 6/4, 2019 at 18:17 Comment(0)
S
0

i am getting same error in angular 8

1>> i upgrade it to 9 & do lots of config change in project NOT RESOLVE

2>> i make all the changes on stackOverflow & github but nothig works NOT RESOLVE

for me a library crossing internally @HostListener ie angular2-multiselect-dropdown (you can easily find it on npm)

which is giving error like Directive ɵc, Expected 2 arguments, but got 1

(sometimes AOT compile it but most of time not ) but each time i run command npm run build:ssr

finally after spending more than a day i remove this library (angular2-multiselect-dropdown)and all works fine me

Strengthen answered 25/2, 2020 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.