在Angular 2+中加载组件后如何自动按钮单击

时间:2018-12-14 14:25:00

标签: javascript html angular typescript single-page-application

我目前正在尝试在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>

我目前正在尝试使用生命周期挂钩ngAfterContentInit()调用this.onSearch()函数,但是此方法不起作用。看来函数调用是在组件加载时进行的,但从未完成。

     @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 :(得分:0)

ngAfterContentInit添加一些console.log语句,看看是否可以打印。 在内部和外部将其添加,查看打印的内容。 在创建组件的子视图之后,Angular会调用AfterViewInit()和AfterViewChecked()挂钩。

您的组件还应该实现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)
       }
     }

   }

答案 1 :(得分:0)

如果您想在onSearch()中调用ngAfterContentInit()方法,则可以这样做。

在.html中定义模板变量#buttonSearch

.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)
    }
}