Ошибка ViewChild: ожидается 2 аргумента, но получено 1.ts (2554) core.d.ts (8054, 47): аргумент для 'opts' не предоставлен

В этой строке следующего кода @ViewChild('myListView') listViewComponent: RadListViewComponent; я получаю следующее сообщение об ошибке:

Ожидается 2 аргумента, но получено 1.ts (2554) core.d.ts (8054, 47): аргумент для opts не указан.

Поскольку я новичок, просто следуя руководству 2017 года, я понятия не имею, почему это происходит и как это исправить? Но похоже, что реализация декоратора ViewChild() изменилась, хотя я не знаю, как адаптировать свой код, чтобы это исправить?

import { Component, OnInit, Inject, ViewChild, ChangeDetectorRef } from '@angular/core'; 
import { View } from 'tns-core-modules/ui/core/view';
import { FavoriteService } from '../services/favorite.service'; 
import { Dish } from '../shared/dish'; 
import { ListViewEventData, RadListView } from 'nativescript-ui-listview'; 
import { RadListViewComponent } from 'nativescript-ui-listview/angular'; 
import { ObservableArray } from 'tns-core-modules/data/observable-array'; 
import { DrawerPage } from '../shared/drawer/drawer.page'; 
import { confirm } from "tns-core-modules/ui/dialogs"; 
import { Toasty, ToastDuration, ToastPosition } from 'nativescript-toasty';


@Component({ 
    selector: 'app-favorites', 
    moduleId: module.id, 
    templateUrl: './favorites.component.html', 
    styleUrls: ['./favorites.component.css'] 
}) 
export class FavoritesComponent extends DrawerPage implements OnInit {
    
    favorites: ObservableArray<Dish>; 
    errMess: string;

    @ViewChild('myListView') listViewComponent: RadListViewComponent;
    
    constructor(private favoriteservice: FavoriteService, 
        private changeDetectorRef: ChangeDetectorRef,        
        @Inject('BaseURL') private BaseURL) { 
            super(changeDetectorRef); 
        }


    ngOnInit() { 
        this.favoriteservice.getFavorites() 
        .subscribe(favorites => this.favorites = new ObservableArray (favorites), 
        errmess => this.errMess = errmess); 
    }

    deleteFavorite(id: number) { 
        console.log('delete', id);

        let options = { 
            title: "Confirm Delete", 
            message: 'Do you want to delete Dish '+ id, 
            okButtonText: "Yes", 
            cancelButtonText: "No", 
            neutralButtonText: "Cancel" 
        };

        confirm(options).then((result: boolean) => { 
            if(result) {
                this.favorites = null;
                this.favoriteservice.deleteFavorite(id) 
                .subscribe(favorites => { 
                    //const toast = new Toasty("Deleted Dish "+ id, "short", "bottom" ); 
                    //toast.show();
                    const toasty = new Toasty({ text: "Deleted Dish "+ id })
                    .setToastDuration(ToastDuration.SHORT)
                    .setToastPosition(ToastPosition.BOTTOM)
                    //.setTextColor(new Color('white'))
                    //.setBackgroundColor('#ff9999')
                    .show();  
                    this.favorites = new ObservableArray(favorites); 
                }, 
                errmess => this.errMess = errmess);
            } 
            else { 
                console.log('Delete cancelled'); 
            }
        });
    }    

    public onCellSwiping(args: ListViewEventData) { 
        var swipeLimits = args.data.swipeLimits; 
        var currentItemView = args.object; 
        var currentView;

        if(args.data.x > 200) {

        } 
        else if (args.data.x < -200) {
        }
    }

    public onSwipeCellStarted(args: ListViewEventData) { 
        var swipeLimits = args.data.swipeLimits; 
        var swipeView = args['object'];
        var leftItem = swipeView.getViewById<View>('mark-view'); 
        var rightItem = swipeView.getViewById<View>('delete-view'); 
        swipeLimits.left = leftItem.getMeasuredWidth(); 
        swipeLimits.right = rightItem.getMeasuredWidth(); 
        swipeLimits.threshold = leftItem.getMeasuredWidth()/2;
    }
    public onSwipeCellFinished(args: ListViewEventData) {
    }

    public onLeftSwipeClick(args: ListViewEventData) { 
        console.log('Left swipe click'); 
        this.listViewComponent.listView.notifySwipeToExecuteFinished(); 
    }

    public onRightSwipeClick(args: ListViewEventData) { 
        this.deleteFavorite(args.object.bindingContext.id); 
        this.listViewComponent.listView.notifySwipeToExecuteFinished(); 
    }
}

person user3486308    schedule 12.07.2019    source источник


Ответы (2)


В v8 синтаксис ViewChild изменен. CHANGELOG говорит

"Ядро: в Angular версии 8 требуется, чтобы все запросы @ViewChild и @ContentChild имели" статический "флаг, указывающий, является ли запрос" статическим "или" динамическим ". Компилятор ранее сортировал запросы автоматически, но в версии 8.0 требуются разработчики. чтобы явно указать, какое поведение требуется. Это временное требование как часть миграции; см. https://v8.angular.io/guide/static-query-migration для получения дополнительных сведений. "

Я рекомендую использовать https://github.com/angular/angular/blob/master/CHANGELOG.md для обновления

person Imran Khan    schedule 03.11.2019

Если вы используете angular8, декоратор ViewChild() изменился: https://angular.io/guide/static-query-migration, поэтому отсутствует staticпараметр @ViewChild('myListView', {static: false}) listViewComponent: RadListViewComponent;

person Gilsido    schedule 12.07.2019