Как автоматизировать нажатие кнопки после загрузки компонента в Angular 2+ - PullRequest
0 голосов
/ 14 декабря 2018

В настоящее время я пытаюсь запустить функцию поиска после загрузки компонента в Angular.В настоящее время функция вызывается нажатием кнопки, но я хотел бы автоматизировать это.

<button mat-raised-button class="mat-white-button green-button" (click)="onSearch()" style="width: 184px; top: -5px;">
                <i class="fa fa-search" style="margin-bottom: 2px;"></i>&nbsp; Find Shoppers
            </button>

В настоящее время я пытаюсь вызвать функцию this.onSearch () с помощью ловушки жизненного цикла ngAfterContentInit (), однако это не работает.Похоже, что вызов функции выполняется при загрузке компонента, но никогда не завершается.

     @Component({
    templateUrl: 'search.screen.html',
})

export class SearchScreen implements OnInit {

    _dealerId: number;
    public searching: boolean;
    public form: FormGroup;
    public noResultsFound: boolean;
    public viewChecked = false;

    startDate: Date;
    endDate: Date;
    minDate: Date;
    maxDate: Date;

    private searchSubscription: Subscription;

    // for the mat-header table component
    displayedColumns = ['name', 'email', 'phone', 'stage', 'currentVehicle', 'topVehicle', 'mappedDate'];
    shopperCount: number;

    dataSource: MatTableDataSource<SearchResult> = new MatTableDataSource<ActiveShopperSearchResult>();

    private paginator: MatPaginator;
    private sort: MatSort;

    @ViewChild(MatSort) set matSort(ms: MatSort) {
        this.sort = ms;
        this.setDataSourceAttributes();
    }

    @ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
        this.paginator = mp;
        this.setDataSourceAttributes();
    }

    constructor(
        private everestApiService: EverestApiService,
        private _router: Router,
        private dialog: MatDialog,
        private _route: ActivatedRoute,
        private perms: PermissionsService,
    ) {
        this.form = new FormGroup({
            name: new FormControl(null),
            phone: new FormControl(null),
            email: new FormControl(null),
        });
    }

    ngOnInit() {
        this._dealerId = +this._route.snapshot.params['dealerId'];

        let startDateOffset = (24 * 60 * 60 * 1000) * 30; // 30 days offset
        let startDate = new Date();
        startDate.setTime(startDate.getTime() - startDateOffset);
        this.startDate = new Date(startDate.toString());
        this.endDate = new Date();

        let minDateOffset = (24 * 60 * 60 * 1000) * 365;
        let minDate = new Date();
        minDate.setTime(minDate.getTime() - minDateOffset);
        // this.onSearch();

    }
    ngAfterContentInit() {
        if(this.viewChecked === false) {
        this.onSearch();
        console.log(this.viewChecked)
        this.viewChecked = true;
        console.log(this.viewChecked)


        }
    }

 onSearch() {
        console.log('searching');
        this.clearResults();
        let searchParams = '?startDate=' + this.startDate.toISOString().substr(0, 10)
            + '&endDate=' + this.endDate.toISOString().substr(0, 10);

        if (this.form.value.name) {
            searchParams += '&name=' + this.form.value.name;
        }

        if (this.form.value.email) {
            searchParams += '&email=' + this.form.value.email;
        }

        if (this.form.value.phone) {
            searchParams += '&phone=' + this.form.value.phone;
        }

        this.searchSubscription = this.everestApiService.searchActiveShoppers(this._dealerId, searchParams)
            .pipe(track(inProgress => this.searching = inProgress))
            .subscribe((data) => {
                this.dataSource = new MatTableDataSource<ActiveShopperSearchResult>();
                this.dataSource.data = data;
                this.shopperCount = data.length;
                if (data.length === 0) {
                    this.noResultsFound = true;
                }
            });
    }

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

Если вы хотите вызвать метод onSearch() в ngAfterContentInit(), вы можете сделать это.

Определить переменную шаблона #buttonSearch в .html

.html

<button #buttonSearch mat-raised-button class="mat-white-button green-button" (click)="onSearch()" style="width: 184px; top: -5px;">
<i class="fa fa-search" style="margin-bottom: 2px;"></i>&nbsp; Find Shoppers
</button>

И отправить это событие

.ts

@ViewChild('buttonSearch') private buttonSearch : ElementRef

ngAfterContentInit() {
    if(this.viewChecked === false) {
    let event = new Event('click')

    this.buttonSearch.nativeElement.dispatchEvent(event)

    console.log(this.viewChecked)
    this.viewChecked = true;
    console.log(this.viewChecked)
    }
}
0 голосов
/ 14 декабря 2018

добавить некоторые операторы console.log к ngAfterContentInit, посмотреть, печатает ли он.добавьте его внутрь, если и снаружи, посмотрите, что напечатано.Ловушки AfterViewInit () и AfterViewChecked () вызываются Angular после создания дочерних представлений компонента.

Также ваш Компонент должен реализовывать implements AfterViewChecked:

 export class SearchScreen implements OnInit, AfterViewChecked  { 

       ngAfterContentInit() {
        if(this.viewChecked === false) {
        this.onSearch();
        console.log(this.viewChecked)
        this.viewChecked = true;
        console.log(this.viewChecked)
       }
     }

   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...