Background
I've inserted a bunch of content controls into my word document. Each content control is a bit of text e.g. "Hello world".
What I'm trying to do
When a user puts their cursor within the content control I want to access the details of the content control within my add-in.
What I've tried
I run this at startup.
Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, () => {
Word.run( async (context) => {
const range = context.document.getSelection();
console.log({range});
const contentControls = range.contentControls;
contentControls.load("items");
await context.sync();
console.log('contentControls.items', contentControls.items)
})
})
Problem
If a user pops their cursor in the content control no "items" are reported. However if a user highlights the whole content control the "items" are correctly reported.
Question
Is there a way to detect if a user is within a content control without them having to select the whole thing?
Try using Range.parentContentControl (or parentContentControlOrNullObject) to get a reference to the containing content control.
For example,
const parentContentControl = range.parentContentControlOrNullObject;
await context.sync();
if (parentContentControl.isNullObject) {
console.log("The cursor is not in a content control")
}
else {
console.log('parentContentControl', parentContentControl);
}